diff --git a/Gulpfile.ts b/Gulpfile.ts index 1b902562832..295a7ce03d9 100644 --- a/Gulpfile.ts +++ b/Gulpfile.ts @@ -551,7 +551,7 @@ function restoreSavedNodeEnv() { process.env.NODE_ENV = savedNodeEnv; } -let testTimeout = 20000; +let testTimeout = 40000; function runConsoleTests(defaultReporter: string, runInParallel: boolean, done: (e?: any) => void) { const lintFlag = cmdLineOptions["lint"]; cleanTestDirs((err) => { diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 3c003313c8b..a65770c7e34 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. @@ -1124,6 +1129,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. @@ -4248,6 +4258,7 @@ interface KeyAlgorithm { } interface KeyboardEventInit extends EventModifierInit { + code?: string; key?: string; location?: number; repeat?: boolean; @@ -6410,7 +6421,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 +7484,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 +7553,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 +7808,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 +8589,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 +8764,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 +10029,7 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { */ type: string; import?: Document; + integrity: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10300,7 +10318,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 +10891,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 +11897,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 +13270,7 @@ interface PerformanceTiming { readonly responseStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly secureConnectionStart: number; toJSON(): any; } @@ -15527,8 +15548,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 +17090,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 +17145,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 +18175,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 +18232,7 @@ interface EcdsaParams extends Algorithm { } interface EcKeyGenParams extends Algorithm { - typedCurve: string; + namedCurve: string; } interface EcKeyAlgorithm extends KeyAlgorithm { @@ -18330,6 +18368,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 +18445,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 +18539,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 +18592,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 +18750,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.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index c7c7afb821b..f8eba591033 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -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 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, + * 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; +} + 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.es5.d.ts b/lib/lib.es5.d.ts index e082101411d..666e5ef969a 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. @@ -1124,6 +1129,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. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 8e9de3f4ec9..084ed4e8a1a 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. @@ -1124,6 +1129,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. @@ -4190,6 +4200,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 +4362,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 +4479,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 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, + * 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; +} + interface RegExp { /** * Returns a string indicating the flags of the regular expression in question. This field is read-only. @@ -4754,6 +4792,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; @@ -5808,6 +5866,7 @@ interface KeyAlgorithm { } interface KeyboardEventInit extends EventModifierInit { + code?: string; key?: string; location?: number; repeat?: boolean; @@ -7970,7 +8029,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 +9092,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 +9161,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 +9416,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 +10197,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 +10372,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 +11637,7 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { */ type: string; import?: Document; + integrity: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11860,7 +11926,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 +12499,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 +13505,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 +14878,7 @@ interface PerformanceTiming { readonly responseStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly secureConnectionStart: number; toJSON(): any; } @@ -17087,8 +17156,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 +18698,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 +18753,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 +19783,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 +19840,7 @@ interface EcdsaParams extends Algorithm { } interface EcKeyGenParams extends Algorithm { - typedCurve: string; + namedCurve: string; } interface EcKeyAlgorithm extends KeyAlgorithm { @@ -19890,6 +19976,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 +20053,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 +20147,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 +20200,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 +20358,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.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 05a903f9014..0c05ab54ed7 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -64,8 +64,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 +158,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 +191,31 @@ var ts; return undefined; } ts.forEach = forEach; - function contains(array, value, areEqual) { + 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; } } @@ -165,19 +257,43 @@ 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_3 = array; _i < array_3.length; _i++) { + var item = array_3[_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++) { @@ -214,11 +330,15 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + loop: 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); + 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; @@ -328,96 +448,117 @@ 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 isEmpty(map) { - for (var id in map) { - if (hasProperty(map, id)) { - return false; + 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 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.isEmpty = isEmpty; + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + var result = createMap(); + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var value = array_8[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToMap = arrayToMap; + 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; - 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)); - } - } - } - return result; - } - ts.reduceProperties = reduceProperties; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -439,9 +580,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) { @@ -850,10 +989,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++) { @@ -876,7 +1020,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += "(/.+?)?"; + subpattern += doubleAsteriskRegexFragment; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -888,6 +1032,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; } @@ -908,8 +1062,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); @@ -1008,6 +1168,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) { @@ -1070,9 +1231,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"; } @@ -1281,13 +1446,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(); @@ -1296,23 +1461,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]; - } + (fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback); } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -1324,8 +1484,9 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); + var callbacks = fileWatcherCallbacks[filePath]; + if (callbacks) { + var newCallbacks = ts.copyListRemovingItem(callback, callbacks); if (newCallbacks.length === 0) { delete fileWatcherCallbacks[filePath]; } @@ -1338,7 +1499,7 @@ var ts; 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); @@ -2032,6 +2193,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." }, @@ -2079,6 +2241,9 @@ 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." }, 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}'." }, @@ -2149,7 +2314,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}'." }, @@ -2177,6 +2342,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." }, @@ -2297,6 +2463,7 @@ var ts; 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." }, 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." }, @@ -2356,7 +2523,7 @@ var ts; return token >= 69; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = { + var textToToken = ts.createMap({ "abstract": 115, "any": 117, "as": 116, @@ -2480,7 +2647,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,]; @@ -2521,9 +2688,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; } @@ -3890,24 +4055,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; @@ -3925,7 +4072,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -3934,14 +4081,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; } @@ -3960,7 +4107,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; @@ -4060,16 +4207,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); @@ -4683,6 +4834,7 @@ var ts; case 155: return node.typeName; case 194: + ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69: case 139: @@ -5112,7 +5264,7 @@ 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; @@ -5159,6 +5311,7 @@ var ts; case 146: case 225: case 232: + case 228: case 142: case 253: case 145: @@ -5275,9 +5428,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; @@ -5497,7 +5654,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = {}; + var fileDiagnostics = ts.createMap(); var diagnosticsModified = false; var modificationCount = 0; return { @@ -5511,12 +5668,12 @@ var ts; return modificationCount; } function reattachFileDiagnostics(newFile) { - if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) { - return; - } - for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) { - var diagnostic = _a[_i]; - diagnostic.file = newFile; + var diagnostics = fileDiagnostics[newFile.fileName]; + if (diagnostics) { + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + diagnostic.file = newFile; + } } } function add(diagnostic) { @@ -5550,9 +5707,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); } @@ -5563,15 +5718,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", @@ -5584,7 +5737,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" - }; + }); function escapeString(s) { s = escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, getReplacement) : s; return s; @@ -6065,21 +6218,11 @@ var ts; isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 69) { - return true; - } - else if (isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } + 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); @@ -6108,6 +6251,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; @@ -6164,7 +6311,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 @@ -6358,7 +6505,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.parseTime = 0; var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -6481,6 +6627,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); @@ -6759,14 +6907,17 @@ var ts; case 280: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); + 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; @@ -6801,7 +6952,7 @@ var ts; var sourceFile; var parseDiagnostics; var syntaxCursor; - var token; + var currentToken; var sourceText; var nodeCount; var identifiers; @@ -6829,7 +6980,7 @@ var ts; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = {}; + identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; contextFlags = scriptKind === 1 || scriptKind === 2 ? 134217728 : 0; @@ -6851,10 +7002,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; @@ -7018,26 +7169,29 @@ 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 speculationHelper(callback, isLookAhead) { - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var saveContextFlags = contextFlags; @@ -7046,7 +7200,7 @@ var ts; : scanner.tryScan(callback); ts.Debug.assert(saveContextFlags === contextFlags); if (!result || isLookAhead) { - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -7059,20 +7213,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(); } @@ -7087,14 +7241,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; @@ -7104,19 +7258,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; @@ -7158,14 +7312,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(); @@ -7177,18 +7331,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(); @@ -7200,7 +7354,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); @@ -7210,7 +7364,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token === t && tryParse(nextTokenCanFollowModifier); + return token() === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -7220,39 +7374,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); @@ -7263,21 +7417,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) { @@ -7289,23 +7443,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: @@ -7318,7 +7472,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; @@ -7331,11 +7485,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; @@ -7345,7 +7499,7 @@ var ts; return isStartOfExpression(); } function isListTerminator(kind) { - if (token === 1) { + if (token() === 1) { return true; } switch (kind) { @@ -7357,49 +7511,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; @@ -7654,7 +7808,7 @@ var ts; break; } parseExpected(24); - if (considerSemicolonAsDelimiter && token === 23 && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -7699,7 +7853,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); @@ -7724,7 +7878,7 @@ var ts; var span = createNode(197); span.expression = allowInAnd(parseExpression); var literal; - if (token === 16) { + if (token() === 16) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -7734,14 +7888,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); @@ -7767,7 +7918,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); @@ -7804,7 +7955,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token === 25) { + if (token() === 25) { return parseBracketedList(17, parseTypeParameter, 25, 27); } } @@ -7815,7 +7966,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 || token === 97; + return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; } function setModifiers(node, modifiers) { if (modifiers) { @@ -7825,7 +7976,7 @@ var ts; } function parseParameter() { var node = createNode(142); - if (token === 97) { + if (token() === 97) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); @@ -7834,7 +7985,7 @@ var ts; setModifiers(node, 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 && node.flags === 0 && ts.isModifierKind(token())) { nextToken(); } node.questionToken = parseOptionalToken(53); @@ -7892,17 +8043,17 @@ var ts; return 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; @@ -7914,14 +8065,14 @@ 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); @@ -7935,7 +8086,7 @@ 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.name = name; @@ -7950,7 +8101,7 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token === 56) { + if (token() === 56) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); @@ -7959,34 +8110,34 @@ var ts; } 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 || 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(); @@ -7998,7 +8149,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token === 17 || token === 25; + return token() === 17 || token() === 25; } function parseTypeLiteral() { var node = createNode(159); @@ -8038,10 +8189,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: @@ -8052,13 +8212,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 { @@ -8078,7 +8243,7 @@ var ts; } } function isStartOfType() { - switch (token) { + switch (token()) { case 117: case 132: case 130: @@ -8095,7 +8260,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: @@ -8104,7 +8274,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token === 18 || isStartOfParameter() || isStartOfType(); + return token() === 18 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -8118,7 +8288,7 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token === operator) { + if (token() === operator) { var types = [type]; types.pos = type.pos; while (parseOptional(operator)) { @@ -8138,20 +8308,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; @@ -8160,17 +8330,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; } } @@ -8192,7 +8362,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -8204,7 +8374,7 @@ var ts; if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156); } - if (token === 92) { + if (token() === 92) { return parseFunctionOrConstructorType(157); } return parseUnionTypeOrHigher(); @@ -8213,7 +8383,7 @@ var ts; return parseOptional(54) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { - switch (token) { + switch (token()) { case 97: case 95: case 93: @@ -8241,7 +8411,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -8263,10 +8433,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() { @@ -8285,8 +8455,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; } } @@ -8302,7 +8472,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())) { @@ -8311,7 +8481,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token === 114) { + if (token() === 114) { if (inYieldContext()) { return true; } @@ -8327,7 +8497,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); @@ -8337,7 +8507,7 @@ 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); @@ -8368,7 +8538,7 @@ var ts; return undefined; } var isAsync = !!(arrowFunction.flags & 256); - var lastToken = token; + var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 || lastToken === 15) ? parseArrowFunctionExpressionBody(isAsync) @@ -8376,25 +8546,25 @@ var ts; return 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) { @@ -8457,7 +8627,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token === 118) { + if (token() === 118) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -8468,13 +8638,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; } } @@ -8488,18 +8658,18 @@ var ts; 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); @@ -8532,16 +8702,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; } @@ -8557,13 +8727,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: @@ -8618,7 +8788,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -8642,7 +8812,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token === 119) { + if (token() === 119) { if (inAwaitContext()) { return true; } @@ -8657,18 +8827,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); @@ -8680,7 +8847,7 @@ var ts; return simpleUnaryExpression; } function parseSimpleUnaryExpression() { - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -8694,12 +8861,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: @@ -8707,6 +8878,7 @@ var ts; case 78: case 101: case 103: + case 119: return false; case 25: if (sourceFile.languageVariant !== 1) { @@ -8717,29 +8889,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); @@ -8750,7 +8922,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); @@ -8789,7 +8961,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); @@ -8806,11 +8978,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: @@ -8818,7 +8990,7 @@ 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 = []; @@ -8826,11 +8998,11 @@ var ts; 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; } @@ -8846,7 +9018,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token === 27) { + if (token() === 27) { node = createNode(243, fullStart); scanJsxText(); } @@ -8867,7 +9039,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); @@ -8880,7 +9052,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248); parseExpected(15); - if (token !== 16) { + if (token() !== 16) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -8893,14 +9065,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) { + switch (token()) { case 9: node.initializer = parseLiteralNode(); break; @@ -8950,7 +9122,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; @@ -8960,7 +9132,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; @@ -8971,10 +9143,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); @@ -8986,7 +9158,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; @@ -8998,7 +9170,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(); @@ -9027,7 +9199,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token) { + switch (token()) { case 17: case 21: case 18: @@ -9054,7 +9226,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token) { + switch (token()) { case 8: case 9: case 11: @@ -9107,8 +9279,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() { @@ -9145,10 +9317,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; @@ -9211,7 +9383,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); @@ -9284,8 +9456,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 { @@ -9311,11 +9483,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); @@ -9367,7 +9539,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token === 71 ? parseCaseClause() : parseDefaultClause(); + return token() === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213); @@ -9393,8 +9565,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); } @@ -9434,19 +9606,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: @@ -9474,16 +9646,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; @@ -9499,7 +9671,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token) { + switch (token()) { case 55: case 23: case 15: @@ -9547,13 +9719,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: @@ -9625,7 +9797,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token) { + switch (token()) { case 102: case 108: case 74: @@ -9648,7 +9820,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: nextToken(); - switch (token) { + switch (token()) { case 77: case 56: return parseExportAssignment(fullStart, decorators, modifiers); @@ -9669,17 +9841,17 @@ var ts; } 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); @@ -9692,7 +9864,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 { @@ -9718,13 +9890,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(); @@ -9733,14 +9905,14 @@ 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: @@ -9753,7 +9925,7 @@ var ts; ts.Debug.fail(); } nextToken(); - if (token === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -9827,7 +9999,7 @@ var ts; 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 { @@ -9860,31 +10032,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: @@ -9922,8 +10094,8 @@ var ts; 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; } @@ -9949,9 +10121,9 @@ var ts; 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; @@ -9963,7 +10135,7 @@ var ts; return modifiers; } function parseClassElement() { - if (token === 23) { + if (token() === 23) { var result = createNode(198); nextToken(); return finishNode(result); @@ -9975,17 +10147,17 @@ 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) { @@ -10023,7 +10195,7 @@ var ts; : undefined; } function isImplementsClause() { - return token === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { if (isHeritageClause()) { @@ -10032,9 +10204,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); @@ -10044,13 +10216,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); @@ -10126,14 +10298,14 @@ var ts; var node = createNode(225, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - if (token === 137) { + if (token() === 137) { node.name = parseIdentifier(); node.flags |= 131072; } else { node.name = parseLiteralNode(true); } - if (token === 15) { + if (token() === 15) { node.body = parseModuleBlock(); } else { @@ -10143,7 +10315,7 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (token === 137) { + if (token() === 137) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } else if (parseOptional(126)) { @@ -10151,14 +10323,14 @@ var ts; } 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() { @@ -10183,7 +10355,7 @@ 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); @@ -10198,8 +10370,8 @@ var ts; importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || - token === 37 || - token === 15) { + token() === 37 || + token() === 15) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136); } @@ -10214,7 +10386,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); } @@ -10232,7 +10404,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token === 9) { + if (token() === 9) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -10261,14 +10433,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(); @@ -10291,7 +10463,7 @@ var ts; } else { node.exportClause = parseNamedImportsOrExports(237); - if (token === 136 || (token === 9 && !scanner.hasPrecedingLineBreak())) { + if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } @@ -10390,7 +10562,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token) { + switch (token()) { case 37: case 53: case 17: @@ -10403,13 +10575,13 @@ 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); scanner.setText(content, start, length); - token = scanner.scan(); + currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -10427,12 +10599,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; @@ -10443,20 +10615,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(); @@ -10469,7 +10641,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token) { + switch (token()) { case 37: return parseJSDocAllType(); case 53: @@ -10496,7 +10668,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(); } @@ -10527,7 +10707,7 @@ var ts; result.parameters = parseDelimitedList(22, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18); - if (token === 54) { + if (token() === 54) { nextToken(); result.type = parseJSDocType(); } @@ -10544,12 +10724,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; } @@ -10592,7 +10772,7 @@ var ts; function parseJSDocRecordMember() { var result = createNode(266); result.name = parseSimplePropertyName(); - if (token === 54) { + if (token() === 54) { nextToken(); result.type = parseJSDocType(); } @@ -10641,15 +10821,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); } @@ -10669,14 +10854,14 @@ var ts; } 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; @@ -10700,8 +10885,8 @@ var ts; var canParseTag = true; var seenAsterisk = true; nextJSDocToken(); - while (token !== 1) { - switch (token) { + while (token() !== 1) { + switch (token()) { case 55: if (canParseTag) { parseTag(); @@ -10739,12 +10924,12 @@ var ts; return finishNode(result, end); } function skipWhitespace() { - while (token === 5 || token === 4) { + while (token() === 5 || token() === 4) { nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(token === 55); + ts.Debug.assert(token() === 55); var atToken = createNode(55, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -10790,7 +10975,7 @@ var ts; } } function tryParseTypeExpression() { - if (token !== 15) { + if (token() !== 15) { return undefined; } var typeExpression = parseJSDocTypeExpression(); @@ -10809,7 +10994,7 @@ var ts; } parseExpected(20); } - else if (ts.tokenIsIdentifierOrKeyword(token)) { + else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); } if (!name) { @@ -10902,9 +11087,9 @@ 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); @@ -10936,7 +11121,7 @@ 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(); @@ -10978,7 +11163,7 @@ var ts; typeParameter.name = name_9; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token === 24) { + if (token() === 24) { nextJSDocToken(); } else { @@ -10994,10 +11179,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) { @@ -11077,8 +11262,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } } @@ -11150,8 +11335,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; visitNode(node); } return; @@ -11303,7 +11488,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.bindTime = 0; function getModuleInstanceState(node) { if (node.kind === 222 || node.kind === 223) { return 0; @@ -11341,9 +11525,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() { @@ -11376,7 +11561,7 @@ var ts; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; + classifiableNames = ts.createMap(); symbolCount = 0; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { @@ -11415,10 +11600,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; @@ -11502,35 +11687,38 @@ var ts; var isDefaultExport = node.flags & 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 (declaration.flags & 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; @@ -11548,8 +11736,8 @@ var ts; else { if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192)) { 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; @@ -11566,7 +11754,7 @@ var ts; if (containerFlags & 1) { container = blockScopeContainer = node; if (containerFlags & 32) { - container.locals = {}; + container.locals = ts.createMap(); } addToContainerChain(container); } @@ -11741,15 +11929,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: @@ -11758,9 +11940,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: @@ -11782,10 +11963,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, @@ -11829,7 +12006,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingSwitchStatement(switchStatement)) { + if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -12417,12 +12594,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) { @@ -12461,7 +12638,7 @@ var ts; } default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; + blockScopeContainer.locals = ts.createMap(); addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -12674,7 +12851,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: @@ -12690,7 +12867,7 @@ 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; return; @@ -12732,10 +12909,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: @@ -12784,15 +12961,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) { @@ -12814,7 +12990,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) { @@ -12845,18 +13021,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; @@ -12870,7 +13048,7 @@ var ts; return; } if (!funcSymbol.members) { - funcSymbol.members = {}; + funcSymbol.members = ts.createMap(); } declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } @@ -12900,7 +13078,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; } @@ -13037,7 +13215,6 @@ var ts; return node.id; } ts.getNodeId = getNodeId; - ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -13054,7 +13231,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); @@ -13110,30 +13287,37 @@ var ts; 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 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 enumNumberIndexInfo = createIndexInfo(stringType, true); - var globals = {}; + var globals = ts.createMap(); var patternAmbientModules; var getGlobalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; @@ -13169,10 +13353,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 = []; @@ -13188,7 +13370,7 @@ var ts; var potentialThisCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); - var typeofEQFacts = { + var typeofEQFacts = ts.createMap({ "string": 1, "number": 2, "boolean": 4, @@ -13196,8 +13378,8 @@ var ts; "undefined": 16384, "object": 16, "function": 32 - }; - var typeofNEFacts = { + }); + var typeofNEFacts = ts.createMap({ "string": 128, "number": 256, "boolean": 512, @@ -13205,16 +13387,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", @@ -13224,15 +13406,13 @@ 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 _displayBuilder; - var builtinGlobals = (_a = {}, - _a[undefinedSymbol.name] = undefinedSymbol, - _a - ); + var builtinGlobals = ts.createMap(); + builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -13258,13 +13438,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) @@ -13278,9 +13458,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; @@ -13301,9 +13481,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; } @@ -13323,12 +13503,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); @@ -13344,28 +13524,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]); } } } @@ -13387,7 +13556,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); } @@ -13398,13 +13567,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) { @@ -13419,23 +13586,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; + } + } } } } @@ -13519,7 +13688,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 || @@ -13556,7 +13725,7 @@ var ts; } result = undefined; } - if (ts.hasProperty(moduleExports, name) && + if (moduleExports[name] && moduleExports[name].flags === 8388608 && ts.getDeclarationOfKind(moduleExports[name], 238)) { break; @@ -13585,7 +13754,7 @@ var ts; case 221: case 192: case 222: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { if (lastLocation && lastLocation.flags & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; @@ -13603,7 +13772,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; } @@ -13654,8 +13823,9 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -13683,7 +13853,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); @@ -13712,33 +13882,30 @@ 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 false; + 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 checkResolvedBlockScopedVariable(result, errorLocation) { 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)); } } @@ -13795,7 +13962,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); @@ -13811,9 +13978,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); } } } @@ -13843,6 +14010,9 @@ var ts; } symbolFromVariable = resolveSymbol(symbolFromVariable); var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_10.text === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; @@ -13862,10 +14032,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) { @@ -13886,7 +14056,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."); @@ -13894,6 +14064,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; @@ -13923,6 +14094,7 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); if (node.kind === 235) { checkExpressionCached(node.expression); } @@ -13939,11 +14111,11 @@ 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) { @@ -13955,7 +14127,7 @@ var ts; } var symbol; if (name.kind === 69) { - var message = meaning === 1536 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; @@ -13964,7 +14136,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); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -14022,7 +14194,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(moduleReferenceLiteral, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + } } return undefined; } @@ -14052,7 +14231,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] = { @@ -14060,7 +14239,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]; } @@ -14078,11 +14257,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); @@ -14091,7 +14270,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++) { @@ -14142,8 +14321,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) { @@ -14151,6 +14330,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; @@ -14165,14 +14350,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); } } } @@ -14190,7 +14373,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; @@ -14215,7 +14398,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) { @@ -14232,10 +14415,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)) { @@ -14262,10 +14445,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; } @@ -14308,7 +14491,7 @@ var ts; 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; @@ -14379,10 +14562,10 @@ 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); @@ -14433,6 +14616,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"; @@ -14555,35 +14763,45 @@ var ts; 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) { + 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) { + 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 & 32) { writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } + else if (type.flags & 64) { + writer.writeStringLiteral(type.text); + } else { writePunctuation(writer, 15); writeSpace(writer); @@ -14606,7 +14824,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); @@ -14628,6 +14846,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; @@ -14649,16 +14872,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); } @@ -14675,7 +14898,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); @@ -15077,13 +15300,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) { @@ -15100,7 +15323,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); } @@ -15141,7 +15364,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) { @@ -15183,7 +15406,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); @@ -15245,7 +15468,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); @@ -15257,7 +15480,7 @@ 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; @@ -15290,7 +15513,7 @@ 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) { @@ -15325,9 +15548,14 @@ 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); } @@ -15339,26 +15567,24 @@ var ts; 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 checkExpressionCached(element.initializer); } 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; @@ -15369,7 +15595,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; }); @@ -15378,27 +15604,27 @@ 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) { 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 e.kind === 193 ? 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); @@ -15443,14 +15669,21 @@ var ts; if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = undefined; + var type = void 0; if (declaration.kind === 187 || declaration.kind === 172 && declaration.parent.kind === 187) { - type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? + if (declaration.flags & 134217728) { + 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); })); + checkExpressionCached(decl.parent.right); }); + type = getUnionType(declaredTypes, true); } - if (type === undefined) { + else { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { @@ -15542,9 +15775,9 @@ var ts; 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; @@ -15595,7 +15828,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); @@ -15655,7 +15888,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); @@ -15682,7 +15915,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 80896) { + if (baseConstructorType.flags & 2588672) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -15698,25 +15931,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); @@ -15737,7 +15973,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; } @@ -15770,7 +16006,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]; @@ -15802,8 +16038,8 @@ var ts; 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; } @@ -15817,20 +16053,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; } @@ -15843,8 +16079,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); @@ -15855,12 +16092,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; } } @@ -15872,19 +16109,80 @@ 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 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] = createType(256); + memberType.symbol = memberSymbol; + memberType.baseType = enumType; + memberType.text = "" + 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; @@ -15908,11 +16206,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); @@ -15983,7 +16284,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; @@ -15991,7 +16292,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); @@ -16001,7 +16302,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; } } @@ -16018,19 +16319,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); @@ -16040,7 +16349,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); @@ -16066,7 +16375,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; @@ -16076,11 +16385,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); @@ -16104,22 +16413,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]; @@ -16165,7 +16458,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; @@ -16190,7 +16483,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); @@ -16250,7 +16543,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)); } @@ -16264,41 +16557,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; } } } @@ -16309,7 +16597,7 @@ var ts; var prop = _c[_b]; getPropertyOfUnionOrIntersectionType(type, prop.name); } - if (type.flags & 16384) { + if (type.flags & 524288) { break; } } @@ -16317,12 +16605,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); @@ -16330,19 +16618,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; @@ -16350,7 +16638,7 @@ 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]; @@ -16369,7 +16657,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 16384) { + else if (containingType.flags & 524288) { return undefined; } } @@ -16382,11 +16670,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 | @@ -16394,47 +16691,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; } @@ -16444,7 +16740,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; } @@ -16469,7 +16765,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes); + return getUnionType(propTypes, true); } } return undefined; @@ -16552,7 +16848,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; @@ -16572,7 +16868,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) { @@ -16598,6 +16894,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; @@ -16608,7 +16907,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; } @@ -16693,7 +16992,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); @@ -16717,7 +17016,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]; } } @@ -16737,7 +17036,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; @@ -16781,7 +17080,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; } @@ -16813,24 +17112,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; @@ -16840,20 +17142,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; @@ -16903,8 +17214,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; @@ -16913,7 +17225,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793056) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -16939,14 +17251,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) : @@ -16981,7 +17293,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; } @@ -16995,7 +17307,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); @@ -17005,8 +17317,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) { @@ -17034,16 +17346,39 @@ 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) { @@ -17051,30 +17386,68 @@ var ts; } 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) { + if (type.flags & 524288) { + addTypesToUnion(typeSet, type.types); + } + else if (type.flags & 1) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && type.flags & 6144) { + if (type.flags & 2048) typeSet.containsUndefined = true; - if (type.flags & 64) + if (type.flags & 4096) typeSet.containsNull = true; - if (!(type.flags & 2097152)) + if (!(type.flags & 33554432)) typeSet.containsNonWideningType = true; } - else if (type !== neverType && !ts.contains(typeSet, type)) { - typeSet.push(type); + else if (!(type.flags & 8192)) { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(type.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])) { @@ -17092,7 +17465,7 @@ var ts; } } } - function getUnionType(types, noSubtypeReduction) { + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -17100,17 +17473,11 @@ 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); } if (typeSet.length === 0) { @@ -17118,78 +17485,103 @@ var ts; 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, getTypeFromTypeNode), 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, getTypeFromTypeNode), 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 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 = checkExpression(node.literal); } return links.resolvedType; } @@ -17228,7 +17620,7 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node) { + function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { switch (node.kind) { case 117: case 258: @@ -17250,11 +17642,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); @@ -17271,9 +17671,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: @@ -17287,7 +17687,7 @@ var ts; case 281: case 269: case 265: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); case 69: case 139: var symbol = getSymbolAtLocation(node); @@ -17333,6 +17733,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) { @@ -17365,7 +17766,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; @@ -17400,7 +17801,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; @@ -17431,9 +17832,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; } @@ -17485,26 +17888,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; @@ -17547,10 +17947,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; @@ -17561,22 +17961,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); @@ -17689,8 +18092,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; @@ -17716,6 +18119,73 @@ var ts; sourceNonRestParamCount; } } + function isEnumTypeRelatedTo(source, target, errorReporter) { + if (source === target) { + return true; + } + if (source.symbol.name !== target.symbol.name || !(source.symbol.flags & 256) || !(target.symbol.flags & 256)) { + return 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 false; + } + } + } + return 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 | 64) && target.flags & 16) + return true; + if (source.flags & 64 && target.flags & 256 && source.text === target.text) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + 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; @@ -17754,6 +18224,16 @@ 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 === target) @@ -17761,78 +18241,50 @@ var ts; 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 & 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; @@ -17845,14 +18297,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; @@ -17860,22 +18312,25 @@ var ts; } } if (reportErrors) { + if (source.flags & 2588672 && target.flags & 8190) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } 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; @@ -17885,7 +18340,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 || @@ -17894,7 +18349,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)) { @@ -17912,7 +18367,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)) { @@ -17942,14 +18397,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) { @@ -17973,14 +18424,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) { @@ -18052,7 +18499,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = {}; + maybeStack[depth] = ts.createMap(); maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; @@ -18084,7 +18531,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; @@ -18097,7 +18544,7 @@ var ts; } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -18163,7 +18610,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); @@ -18276,7 +18723,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) || @@ -18313,27 +18760,6 @@ 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; @@ -18356,7 +18782,7 @@ 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); @@ -18368,12 +18794,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; @@ -18415,8 +18841,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; @@ -18466,31 +18894,23 @@ 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; - } - return flags; - } function getCommonSupertype(types) { if (!strictNullChecks) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } - 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); + return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -18520,44 +18940,72 @@ 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 isUnitUnionType(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 getBaseTypeOfUnitType(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, getBaseTypeOfUnitType)) : + 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_8 = types; _i < types_8.length; _i++) { + var t = types_8[_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 === emptyStringType ? 32 : 0 : + type.flags & 64 ? type === zeroType ? 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; @@ -18579,7 +19027,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); @@ -18590,7 +19038,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 1048576)) { + if (!(type.flags & 16777216)) { return type; } var regularType = type.regularType; @@ -18600,7 +19048,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; } @@ -18614,31 +19062,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)) { @@ -18646,22 +19091,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))); } @@ -18706,7 +19148,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); } @@ -18748,12 +19190,24 @@ var ts; isFixed: false }; } + 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 inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = {}; + var visited = ts.createMap(); inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -18764,11 +19218,21 @@ 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]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var t = _c[_b]; if (typeIdenticalToSomeType(t, source.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); @@ -18779,8 +19243,8 @@ var ts; 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; @@ -18799,7 +19263,7 @@ var ts; } } } - 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; @@ -18807,20 +19271,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(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -18834,18 +19291,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; } @@ -18853,7 +19308,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (ts.hasProperty(visited, key)) { + if (visited[key]) { return; } visited[key] = true; @@ -18922,8 +19377,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_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -18938,7 +19393,7 @@ 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]; @@ -18950,7 +19405,7 @@ var ts; if (!inferredType) { var inferences = getInferenceCandidates(context, index); if (inferences.length) { - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences, true) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -19016,10 +19471,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: @@ -19031,16 +19482,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; } @@ -19053,6 +19505,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 && + isUnitUnionType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -19079,7 +19565,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++) { @@ -19091,70 +19577,79 @@ 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) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (reducedType !== neverType) { + return reducedType; } } return declaredType; } + function getTypeFactsOfTypes(types) { + var result = 0; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_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 === emptyStringType ? 3030785 : 1982209 : + type === emptyStringType ? 3145473 : 4194049; + } + if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } + if (flags & (64 | 256)) { + var isZero = type === zeroType || type.flags & 256 && 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) { @@ -19248,51 +19743,86 @@ 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 = 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) { return declaredType; @@ -19332,7 +19862,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; } @@ -19351,16 +19881,9 @@ 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)) : + return declaredType.flags & 524288 ? + getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : declaredType; } if (containsMatchingReference(reference, node)) { @@ -19369,37 +19892,55 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var type = getTypeAtFlowNode(flow.antecedent); + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); if (type !== neverType) { var assumeTrue = (flow.flags & 32) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType) { + if (type === neverType && isIncomplete(flowType)) { type = narrowType(declaredType, flow.expression, assumeTrue); } } - 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); } @@ -19408,32 +19949,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) { @@ -19443,26 +20018,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: @@ -19472,23 +20050,34 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + function narrowTypeByEquality(type, operator, value, assumeTrue) { 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 !== neverType ? narrowedType : type; + } + return isUnitType(valueType) ? filterType(type, function (t) { return t !== valueType; }) : 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; @@ -19498,76 +20087,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 === neverType ? 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, t)); }); + return caseType === neverType ? 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; @@ -19580,12 +20133,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) { @@ -19599,23 +20155,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 !== neverType) { + 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, targetType) ? 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); @@ -19623,6 +20178,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) { @@ -19693,20 +20251,48 @@ 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); @@ -19743,16 +20329,22 @@ var ts; 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); + 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 || + flowContainer !== declarationContainer || 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; } @@ -19915,10 +20507,6 @@ var ts; return getInferredClassType(classSymbol); } } - var type = getContextuallyTypedThisType(container); - if (type) { - return type; - } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -19927,7 +20515,7 @@ 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); + return getFlowTypeOfReference(node, type, true, undefined); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -20060,11 +20648,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; @@ -20121,7 +20709,7 @@ 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; @@ -20204,6 +20792,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); } @@ -20223,14 +20814,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_11 = types; _i < types_11.length; _i++) { + var current = types_11[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -20248,7 +20839,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; }); } @@ -20256,7 +20847,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)); @@ -20362,6 +20953,30 @@ var ts; } return undefined; } + function isLiteralTypeLocation(node) { + var parent = node.parent; + switch (parent.kind) { + case 187: + switch (parent.operatorToken.kind) { + case 32: + case 33: + case 30: + case 31: + return true; + } + break; + case 188: + return (node === parent.whenTrue || + node === parent.whenFalse) && + isLiteralTypeLocation(parent); + case 178: + return isLiteralTypeLocation(parent); + case 249: + case 166: + return true; + } + return false; + } function getNonGenericSignature(type) { var signatures = getSignaturesOfStructuredType(type, 0); if (signatures.length === 1) { @@ -20390,13 +21005,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_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -20452,7 +21067,7 @@ var ts; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { - var type = createNewTupleType(elementTypes); + var type = cloneTypeReference(createTupleType(elementTypes)); type.pattern = node; return type; } @@ -20464,7 +21079,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) { @@ -20479,13 +21094,15 @@ 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); @@ -20497,7 +21114,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 { @@ -20513,13 +21130,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 && @@ -20557,7 +21174,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; @@ -20595,7 +21212,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); } @@ -20607,8 +21224,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; } @@ -20662,9 +21279,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) { @@ -20737,7 +21354,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; } @@ -20749,11 +21366,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) { @@ -20776,16 +21393,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; @@ -20838,7 +21455,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; } @@ -20921,7 +21538,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) { @@ -20939,7 +21556,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)); } } @@ -21000,10 +21617,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; } @@ -21012,9 +21629,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); @@ -21035,13 +21652,13 @@ var ts; 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)); + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 268435456 ? apparentType : type)); } return unknownType; } @@ -21060,12 +21677,15 @@ var ts; checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); + if (prop.flags & 8 && isLiteralContextForType(node, propType)) { + propType = getDeclaredTypeOfSymbol(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 isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 @@ -21156,8 +21776,9 @@ var ts; } } } - 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; @@ -21202,7 +21823,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)); } @@ -21266,7 +21887,7 @@ var ts; lastParent = parent_9; } lastSymbol = symbol; - if (signature.hasStringLiterals) { + if (signature.hasLiteralTypes) { specializedIndex++; spliceIndex = specializedIndex; cutoffIndex++; @@ -21340,7 +21961,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) { @@ -21440,9 +22061,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)) { @@ -21546,10 +22165,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 { @@ -21790,8 +22409,8 @@ var ts; 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))) { + (isTypeAny(apparentType) && funcType.flags & 16384) || + (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 524288) && isTypeAssignableTo(funcType, globalFunctionType))) { if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } @@ -21864,6 +22483,18 @@ var ts; var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + if (baseTypes.length) { + var baseType = baseTypes[0]; + if (flags & 16 && + baseType.symbol === declaration.parent.symbol) { + return true; + } + } + } if (flags & 8) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } @@ -21881,7 +22512,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 524288) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -21912,7 +22543,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 524288) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); @@ -22012,7 +22643,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return addTypeKind(type, 32); + return includeFalsyTypes(type, 2048); } } return type; @@ -22024,6 +22655,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); @@ -22121,7 +22758,7 @@ var ts; return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); + type = contextualSignature ? getUnionType(types, true) : getCommonSupertype(types); if (!type) { if (funcIsGenerator) { error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); @@ -22129,7 +22766,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types, true)) : getUnionType(types, true); } } if (funcIsGenerator) { @@ -22159,24 +22796,18 @@ 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 (!isUnitUnionType(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)) { @@ -22226,7 +22857,7 @@ 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)) { @@ -22328,7 +22959,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { error(operand, diagnostic); return false; } @@ -22422,16 +23053,22 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (node.operator === 36 && node.operand.kind === 8 && isLiteralContextForType(node, numberType)) { + return 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); @@ -22454,10 +23091,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_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -22469,20 +23106,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_14 = types; _i < types_14.length; _i++) { + var t = types_14[_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_15 = types; _a < types_15.length; _a++) { + var t = types_15[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -22491,13 +23128,13 @@ 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 (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))) { @@ -22506,10 +23143,10 @@ var ts; return booleanType; } function checkInExpression(left, right, leftType, rightType) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 | 132 | 16777216)) { + 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; @@ -22576,8 +23213,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); @@ -22607,7 +23245,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); @@ -22637,7 +23275,14 @@ var ts; return sourceType; } 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); @@ -22672,15 +23317,15 @@ var ts; case 68: case 46: case 66: - if (leftType.flags & 96) + 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)); } @@ -22694,18 +23339,18 @@ var ts; return numberType; case 35: case 57: - if (leftType.flags & 96) + 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)) { @@ -22737,6 +23382,12 @@ var ts; case 31: case 32: case 33: + var leftIsUnit = isUnitUnionType(leftType); + var rightIsUnit = isUnitUnionType(rightType); + if (!leftIsUnit || !rightIsUnit) { + leftType = leftIsUnit ? getBaseTypeOfUnitType(leftType) : leftType; + rightType = rightIsUnit ? getBaseTypeOfUnitType(rightType) : rightType; + } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -22746,9 +23397,13 @@ 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 : getBaseTypeOfUnitType(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); @@ -22756,8 +23411,8 @@ var ts; 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)); @@ -22842,14 +23497,63 @@ 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 typeContainsLiteralFromEnum(type, enumType) { + if (type.flags & 524288) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 256 && t.baseType === enumType) { + return true; + } + } + } + if (type.flags & 256) { + return type.baseType === enumType; + } + return false; + } + function isLiteralContextForType(node, type) { + if (isLiteralTypeLocation(node)) { + return true; + } + var contextualType = getContextualType(node); + if (contextualType) { + if (contextualType.flags & 16384) { + var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (type === apparentType) { + return true; + } + contextualType = apparentType; + } + if (type.flags & 2) { + return maybeTypeOfKind(contextualType, 32); + } + if (type.flags & 4) { + return maybeTypeOfKind(contextualType, (64 | 256)); + } + if (type.flags & 8) { + return maybeTypeOfKind(contextualType, 128) && !isTypeAssignableTo(booleanType, contextualType); + } + if (type.flags & 16) { + return typeContainsLiteralFromEnum(contextualType, type); + } + } + return false; + } + function checkLiteralExpression(node) { + if (node.kind === 8) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9: + return isLiteralContextForType(node, stringType) ? getLiteralTypeForText(32, node.text) : stringType; + case 8: + return isLiteralContextForType(node, numberType) ? getLiteralTypeForText(64, node.text) : numberType; + case 99: + case 84: + return isLiteralContextForType(node, booleanType) ? node.kind === 99 ? trueType : falseType : booleanType; } - return stringType; } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -22922,10 +23626,6 @@ var ts; } return type; } - function checkNumericLiteral(node) { - checkGrammarNumericLiteral(node); - return numberType; - } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69: @@ -22936,15 +23636,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: @@ -23181,16 +23879,15 @@ var ts; } } 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); } } } @@ -23201,21 +23898,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)); } @@ -23229,7 +23926,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) { @@ -23243,7 +23940,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); } @@ -23385,12 +24082,7 @@ var ts; 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 (!(node.flags & 65536)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -23412,7 +24104,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) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } } if (node.parent.kind !== 171) { checkSourceElement(node.body); @@ -23465,6 +24160,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) { @@ -23734,10 +24432,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; } @@ -23760,7 +24458,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]; @@ -23786,7 +24484,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; @@ -23797,13 +24495,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); @@ -23908,7 +24606,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); @@ -24064,22 +24762,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) && - !parameterIsThisKeyword(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) { @@ -24107,7 +24803,7 @@ var ts; 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); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -24135,14 +24831,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); } } } @@ -24524,7 +25218,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 { @@ -24532,7 +25226,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); @@ -24585,7 +25279,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 { @@ -24600,7 +25294,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; @@ -24611,7 +25305,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 { @@ -24626,7 +25320,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; } @@ -24646,7 +25340,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) || @@ -24655,10 +25349,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; @@ -24683,10 +25377,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; } @@ -24698,7 +25392,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)) { @@ -24829,7 +25523,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); @@ -24854,7 +25548,7 @@ 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]; @@ -24869,7 +25563,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]; } @@ -24891,7 +25585,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]; } @@ -24999,6 +25693,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; })) { @@ -25012,15 +25711,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 { @@ -25144,7 +25843,7 @@ 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++) { @@ -25152,11 +25851,11 @@ var ts; 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)) { + 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; @@ -25194,7 +25893,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); @@ -25517,9 +26216,6 @@ var ts; } } } - if (compilerOptions.noImplicitAny && !node.body) { - reportImplicitAnyError(node, anyType); - } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -25573,19 +26269,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); @@ -25613,8 +26310,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 : @@ -25668,11 +26365,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); } } @@ -25716,7 +26413,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); } @@ -25778,7 +26475,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); @@ -25948,9 +26645,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); @@ -26021,7 +26719,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = {}; + var symbols = ts.createMap(); var memberFlags = 0; if (isInsideWithStatementBody(location)) { return []; @@ -26052,7 +26750,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: @@ -26073,7 +26771,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; } } @@ -26161,15 +26859,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; @@ -26177,13 +26873,13 @@ 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); @@ -26214,7 +26910,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) { @@ -26306,7 +27002,7 @@ 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)) { @@ -26387,7 +27083,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; } }); @@ -26432,7 +27128,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) { @@ -26576,7 +27272,7 @@ 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); @@ -26584,7 +27280,7 @@ var ts; if (constructorType && isConstructorType(constructorType)) { return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } - var typeSymbol = resolveEntityName(typeName, 793056, true); + var typeSymbol = resolveEntityName(typeName, 793064, true); if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; } @@ -26595,22 +27291,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 16)) { + else if (isTypeOfKind(type, 1024)) { return ts.TypeReferenceSerializationKind.VoidType; } - 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)) { @@ -26645,7 +27341,7 @@ 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 || @@ -26662,9 +27358,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; @@ -26708,7 +27401,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; } @@ -26814,7 +27507,7 @@ 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"); }); @@ -26834,7 +27527,7 @@ 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; } @@ -26848,7 +27541,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 = []; @@ -26876,49 +27569,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; @@ -27111,6 +27764,56 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } + 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) { if (languageVersion < 2) { return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); @@ -27343,7 +28046,7 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = {}; + var seen = ts.createMap(); var Property = 1; var GetAccessor = 2; var SetAccessor = 4; @@ -27386,7 +28089,7 @@ var ts; if (effectiveName === undefined) { return "continue"; } - if (!ts.hasProperty(seen, effectiveName)) { + if (!seen[effectiveName]) { seen[effectiveName] = currentKind; } else { @@ -27414,7 +28117,7 @@ var ts; } } 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) { @@ -27422,7 +28125,7 @@ var ts; } var jsxAttr = attr; var name_22 = jsxAttr.name; - if (!ts.hasProperty(seen, name_22.text)) { + if (!seen[name_22.text]) { seen[name_22.text] = true; } else { @@ -27750,6 +28453,7 @@ var ts; node.kind === 229 || node.kind === 236 || node.kind === 235 || + node.kind === 228 || (node.flags & 2) || (node.flags & (1 | 512))) { return false; @@ -27801,7 +28505,6 @@ var ts; return true; } } - var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -27835,6 +28538,7 @@ var ts; ts.getNullSourceMapWriter = getNullSourceMapWriter; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var sourceMapDir; var stopOverridingSpan = false; @@ -27963,6 +28667,9 @@ var ts; if (pos === -1) { return; } + if (extendedDiagnostics) { + ts.performance.mark("beforeSourcemap"); + } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); sourceLinePos.line++; sourceLinePos.character++; @@ -27990,6 +28697,10 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); + if (extendedDiagnostics) { + ts.performance.mark("afterSourcemap"); + ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); + } } function getStartPos(range) { var rangeHasDecorators = !!range.decorators; @@ -28167,9 +28878,7 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { - referencesOutput += "/// " + newLine; - } + referencesOutput += "/// " + newLine; } } return { @@ -28258,11 +28967,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; } } @@ -28414,7 +29123,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) { @@ -28483,14 +29192,14 @@ 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)) { + if (!(name_23 in currentIdentifiers)) { return name_23; } } @@ -28906,7 +29615,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) { @@ -29004,7 +29713,8 @@ 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) { @@ -29540,7 +30250,7 @@ var ts; return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - var entities = { + var entities = ts.createMap({ "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -29794,7 +30504,7 @@ var ts; "clubs": 0x2663, "hearts": 0x2665, "diams": 0x2666 - }; + }); function emitFiles(resolver, host, targetSourceFile) { 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};"; @@ -29820,7 +30530,7 @@ var ts; }; 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 in node.locals) { if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { return false; } @@ -29831,13 +30541,13 @@ var ts; function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = {}; + state.labeledNonLocalBreaks = ts.createMap(); } state.labeledNonLocalBreaks[labelText] = labelMarker; } else { if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = {}; + state.labeledNonLocalContinues = ts.createMap(); } state.labeledNonLocalContinues[labelText] = labelMarker; } @@ -29895,26 +30605,26 @@ var ts; var isOwnFileEmit; var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = (_a = {}, + var moduleEmitDelegates = ts.createMap((_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 = {}, + )); + var bundleEmitDelegates = ts.createMap((_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 = {}; + generatedNameSet = ts.createMap(); nodeToGeneratedName = []; decoratedClassAliases = []; isOwnFileEmit = !isBundledEmit; @@ -29973,8 +30683,8 @@ var ts; } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentFileIdentifiers, name) && - !ts.hasProperty(generatedNameSet, name); + !(name in currentFileIdentifiers) && + !(name in generatedNameSet); } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { @@ -30871,6 +31581,10 @@ var ts; else if (node.parent.kind === 188 && node.parent.condition === node) { return true; } + else if (node.parent.kind === 185 || node.parent.kind === 181 || + node.parent.kind === 182 || node.parent.kind === 183) { + return true; + } return false; } function needsParenthesisForPropertyAccessOrInvocation(node) { @@ -31457,6 +32171,7 @@ var ts; operand.kind !== 181 && operand.kind !== 186 && operand.kind !== 175 && + !(operand.kind === 187 && node.expression.kind === 195) && !(operand.kind === 174 && node.parent.kind === 175) && !(operand.kind === 179 && node.parent.kind === 174) && !(operand.kind === 8 && node.parent.kind === 172)) { @@ -31498,7 +32213,7 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); + return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 @@ -31959,12 +32674,12 @@ var ts; for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { var id = _d[_c]; if (!seen) { - seen = {}; + seen = ts.createMap(); } else { write(", "); } - if (!ts.hasProperty(seen, id.text)) { + if (!(id.text in seen)) { emit(id); seen[id.text] = id.text; } @@ -32417,7 +33132,7 @@ var ts; } if (convertedLoopState) { if (!convertedLoopState.labels) { - convertedLoopState.labels = {}; + convertedLoopState.labels = ts.createMap(); } convertedLoopState.labels[node.label.text] = node.label.text; } @@ -32515,7 +33230,7 @@ var ts; if (modulekind === ts.ModuleKind.System) { return; } - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + if (!exportEquals && exportSpecifiers && name.text in exportSpecifiers) { for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { var specifier = _b[_a]; writeLine(); @@ -32948,11 +33663,12 @@ var ts; } function emitRestParameter(node) { if (languageVersion < 2 && ts.hasDeclaredRestParameter(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; + var restParam = node.parameters[node.parameters.length - 1]; if (ts.isBindingPattern(restParam.name)) { return; } + var skipThisCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; + var restIndex = node.parameters.length - 1 - skipThisCount; var tempName = createTempVariable(268435456).text; writeLine(); emitLeadingComments(restParam); @@ -33065,7 +33781,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; + var skipCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; var omitCount = languageVersion < 2 && ts.hasDeclaredRestParameter(node) ? 1 : 0; emitList(parameters, skipCount, parameters.length - omitCount - skipCount, false, false); } @@ -33482,12 +34198,7 @@ var ts; emitSignatureParameters(ctor); } else { - if (baseTypeElement) { - write("(...args)"); - } - else { - write("()"); - } + write("()"); } } var startIndex = 0; @@ -33519,7 +34230,7 @@ var ts; write("_super.apply(this, arguments);"); } else { - write("super(...args);"); + write("super(...arguments);"); } emitEnd(baseTypeElement); } @@ -33597,7 +34308,7 @@ var ts; var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192; var generatedName; if (isClassExpressionWithStaticProperties) { - generatedName = getGeneratedNameForNode(node.name); + generatedName = node.name ? getGeneratedNameForNode(node.name) : makeUniqueName("classExpression"); var synthesizedNode = ts.createSynthesizedNode(69); synthesizedNode.text = generatedName; recordTempDeclaration(synthesizedNode); @@ -34047,10 +34758,11 @@ var ts; } if (valueDeclaration) { var parameters = valueDeclaration.parameters; + var skipThisCount = parameters.length && parameters[0].name.originalKeywordKind === 97 ? 1 : 0; var parameterCount = parameters.length; - if (parameterCount > 0) { - for (var i = 0; i < parameterCount; i++) { - if (i > 0) { + if (parameterCount > skipThisCount) { + for (var i = skipThisCount; i < parameterCount; i++) { + if (i > skipThisCount) { write(", "); } if (parameters[i].dotDotDotToken) { @@ -34305,7 +35017,7 @@ var ts; } } function tryRenameExternalModule(moduleName) { - if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { + if (renamedDependencies && moduleName.text in renamedDependencies) { return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; @@ -34605,7 +35317,7 @@ var ts; } function collectExternalModuleInfo(sourceFile) { externalImports = []; - exportSpecifiers = {}; + exportSpecifiers = ts.createMap(); exportEquals = undefined; hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { @@ -34717,7 +35429,7 @@ var ts; if (!hasExportStarsToExportValues) { return undefined; } - if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { + if (!exportedDeclarations && !ts.someProperties(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; @@ -34821,7 +35533,7 @@ var ts; if (hoistedVars) { writeLine(); write("var "); - var seen = {}; + var seen = ts.createMap(); for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; var name_32 = local.kind === 69 @@ -34829,7 +35541,7 @@ var ts; : local.name; if (name_32) { var text = ts.unescapeIdentifier(name_32.text); - if (ts.hasProperty(seen, text)) { + if (text in seen) { continue; } else { @@ -35072,7 +35784,7 @@ var ts; write("System.register("); writeModuleName(node, emitRelativePathAsModuleName); write("["); - var groupIndices = {}; + var groupIndices = ts.createMap(); var dependencyGroups = []; for (var i = 0; i < externalImports.length; i++) { var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); @@ -35080,7 +35792,7 @@ var ts; continue; } var key = text.substr(1, text.length - 2); - if (ts.hasProperty(groupIndices, key)) { + if (key in groupIndices) { var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); continue; @@ -35821,11 +36533,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.programTime = 0; - ts.emitTime = 0; - ts.ioReadTime = 0; - ts.ioWriteTime = 0; - ts.version = "2.1.0"; + ts.version = "2.0.2"; var emptyArray = []; var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { @@ -35908,43 +36616,26 @@ var ts; 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") { @@ -35956,6 +36647,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) { @@ -36178,7 +36878,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); @@ -36302,9 +37002,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); @@ -36312,39 +37012,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) { @@ -36352,7 +37050,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; } @@ -36371,6 +37071,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); @@ -36443,14 +37146,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(); } @@ -36458,9 +37155,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) { @@ -36473,7 +37171,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)) { @@ -36492,11 +37190,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 && @@ -36514,7 +37212,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); @@ -36522,7 +37220,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) { @@ -36563,8 +37262,8 @@ var ts; 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]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; if (diagnostic.file) { var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; var fileName = diagnostic.file.fileName; @@ -36605,25 +37304,17 @@ var ts; return []; } var resolutions = []; - var cache = {}; + var cache = ts.createMap(); 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 result = name_34 in cache + ? cache[name_34] + : cache[name_34] = loader(name_34, 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; } @@ -36634,7 +37325,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)); + } + } } } } @@ -36649,13 +37348,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 maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; var currentNodeModulesDepth = 0; - var modulesWithElidedImports = {}; - var sourceFilesFoundSearchingNodeModules = {}; - var start = new Date().getTime(); + var modulesWithElidedImports = ts.createMap(); + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -36682,10 +37381,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]); @@ -36729,7 +37427,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") { @@ -36748,10 +37447,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; @@ -36774,7 +37473,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); @@ -36864,7 +37563,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 }; @@ -36901,9 +37600,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) { @@ -37042,16 +37742,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) { @@ -37095,8 +37795,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; @@ -37283,7 +37983,7 @@ 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(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) { + if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { sourceFilesFoundSearchingNodeModules[file_1.path] = false; if (!options.noResolve) { processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); @@ -37292,7 +37992,7 @@ var ts; modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } - else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { + else if (file_1 && modulesWithElidedImports[file_1.path]) { if (currentNodeModulesDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); @@ -37344,13 +38044,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) { @@ -37367,7 +38068,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; } @@ -37401,7 +38102,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++) { @@ -37493,6 +38194,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; @@ -37538,7 +38242,7 @@ 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)); @@ -37549,17 +38253,17 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.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 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.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 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } if (options.outDir || @@ -37633,6 +38337,10 @@ var ts; name: "diagnostics", type: "boolean" }, + { + name: "extendedDiagnostics", + type: "boolean" + }, { name: "emitBOM", type: "boolean" @@ -37663,10 +38371,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 }, @@ -37693,7 +38401,7 @@ var ts; { name: "module", shortName: "m", - type: { + type: ts.createMap({ "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -37701,16 +38409,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 }, @@ -37728,6 +38436,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", @@ -37851,12 +38563,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 }, @@ -37885,10 +38597,10 @@ 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 }, { @@ -37989,7 +38701,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", @@ -38011,7 +38723,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 }, @@ -38047,13 +38759,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) { @@ -38066,16 +38784,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 { @@ -38124,10 +38842,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)); @@ -38228,6 +38946,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_35 in options) { + if (ts.hasProperty(options, name_35)) { + switch (name_35) { + case "init": + case "watch": + case "version": + case "help": + case "project": + break; + default: + var value = options[name_35]; + var optionDefinition = optionsNameMap[name_35.toLowerCase()]; + if (optionDefinition) { + var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap) { + result[name_35] = 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_35] = convertedValue; + } + else { + result[name_35] = getNameOfCompilerOptionValue(value, customTypeMap); + } + } + } + break; + } + } + } + return result; + } + } + ts.generateTSConfig = generateTSConfig; function removeComments(jsonText) { var output = ""; var scanner = ts.createScanner(1, false, 0, jsonText); @@ -38245,7 +39033,6 @@ var ts; } return output; } - var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -38320,7 +39107,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; } @@ -38337,7 +39124,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); } @@ -38372,7 +39159,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 { @@ -38393,8 +39180,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); } @@ -38416,12 +39203,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; } } @@ -38456,20 +39240,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_36 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_36)) { continue; } - var match = wildcardDirectoryPattern.exec(name_35); + var match = wildcardDirectoryPattern.exec(name_36); 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_36) ? 1 : 0; + var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1) { @@ -38479,12 +39263,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]; } } } @@ -38497,7 +39279,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; } } @@ -38535,8 +39317,8 @@ var ts; reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost); } function reportDiagnostics(diagnostics, host) { - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; reportDiagnostic(diagnostic, host); } } @@ -38617,21 +39399,21 @@ 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 = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -38862,7 +39644,7 @@ var ts; if (compilerOptions.pretty) { reportDiagnosticWorker = reportDiagnosticWithColorAndContext; } - cachedExistingFiles = {}; + cachedExistingFiles = ts.createMap(); var compileResult = compile(rootFileNames, compilerOptions, compilerHost); if (!ts.isWatchSet(compilerOptions)) { return ts.sys.exit(compileResult.exitStatus); @@ -38871,10 +39653,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) { @@ -38954,12 +39735,9 @@ 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; + if (hasDiagnostics) + ts.performance.enable(); var program = ts.createProgram(fileNames, compilerOptions, compilerHost); var exitStatus = compileProgram(); if (compilerOptions.listFiles) { @@ -38967,7 +39745,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)); @@ -38978,13 +39756,23 @@ 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); + ts.performance.disable(); } return { program: program, exitStatus: exitStatus }; function compileProgram() { @@ -39032,11 +39820,11 @@ var ts; 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) { @@ -39050,21 +39838,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); @@ -39103,58 +39889,10 @@ 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 = {})); diff --git a/lib/tsserver.js b/lib/tsserver.js index 7e0dda1736e..ac670e4dc26 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -69,8 +69,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 +163,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 +196,31 @@ var ts; return undefined; } ts.forEach = forEach; - function contains(array, value, areEqual) { + 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; } } @@ -170,19 +262,43 @@ 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_3 = array; _i < array_3.length; _i++) { + var item = array_3[_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++) { @@ -219,11 +335,15 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + loop: 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); + 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; @@ -333,96 +453,117 @@ 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 isEmpty(map) { - for (var id in map) { - if (hasProperty(map, id)) { - return false; + 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 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.isEmpty = isEmpty; + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + var result = createMap(); + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var value = array_8[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToMap = arrayToMap; + 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; - 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)); - } - } - } - return result; - } - ts.reduceProperties = reduceProperties; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -444,9 +585,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) { @@ -855,10 +994,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++) { @@ -881,7 +1025,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += "(/.+?)?"; + subpattern += doubleAsteriskRegexFragment; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -893,6 +1037,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; } @@ -913,8 +1067,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); @@ -1013,6 +1173,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) { @@ -1075,9 +1236,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"; } @@ -1286,13 +1451,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(); @@ -1301,23 +1466,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]; - } + (fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback); } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -1329,8 +1489,9 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); + var callbacks = fileWatcherCallbacks[filePath]; + if (callbacks) { + var newCallbacks = ts.copyListRemovingItem(callback, callbacks); if (newCallbacks.length === 0) { delete fileWatcherCallbacks[filePath]; } @@ -1343,7 +1504,7 @@ var ts; 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); @@ -2037,6 +2198,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." }, @@ -2084,6 +2246,9 @@ 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." }, 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}'." }, @@ -2154,7 +2319,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}'." }, @@ -2182,6 +2347,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." }, @@ -2302,6 +2468,7 @@ var ts; 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." }, 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." }, @@ -2361,7 +2528,7 @@ var ts; return token >= 69; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = { + var textToToken = ts.createMap({ "abstract": 115, "any": 117, "as": 116, @@ -2485,7 +2652,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,]; @@ -2526,9 +2693,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; } @@ -3869,6 +4034,10 @@ var ts; name: "diagnostics", type: "boolean" }, + { + name: "extendedDiagnostics", + type: "boolean" + }, { name: "emitBOM", type: "boolean" @@ -3899,10 +4068,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 }, @@ -3929,7 +4098,7 @@ var ts; { name: "module", shortName: "m", - type: { + type: ts.createMap({ "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -3937,16 +4106,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 }, @@ -3964,6 +4133,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", @@ -4087,12 +4260,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 }, @@ -4121,10 +4294,10 @@ 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 }, { @@ -4225,7 +4398,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", @@ -4247,7 +4420,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 }, @@ -4283,13 +4456,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) { @@ -4302,16 +4481,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 { @@ -4360,10 +4539,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)); @@ -4464,6 +4643,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); @@ -4481,7 +4730,6 @@ var ts; } return output; } - var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -4556,7 +4804,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; } @@ -4573,7 +4821,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); } @@ -4608,7 +4856,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 { @@ -4629,8 +4877,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); } @@ -4652,12 +4900,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; } } @@ -4692,20 +4937,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) { @@ -4715,12 +4960,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]; } } } @@ -4733,7 +4976,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; } } @@ -4808,24 +5051,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; @@ -4843,7 +5068,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -4852,14 +5077,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; } @@ -4878,7 +5103,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; @@ -4978,16 +5203,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); @@ -5370,9 +5599,9 @@ 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; } } @@ -5601,6 +5830,7 @@ var ts; case 155: return node.typeName; case 194: + ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69: case 139: @@ -5962,8 +6192,8 @@ var ts; var tag = _b[_a]; if (tag.kind === 275) { var parameterTag = tag; - var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_7.text === parameterName) { + var name_8 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_8.text === parameterName) { return parameterTag; } } @@ -6030,7 +6260,7 @@ 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; @@ -6077,6 +6307,7 @@ var ts; case 146: case 225: case 232: + case 228: case 142: case 253: case 145: @@ -6193,9 +6424,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; @@ -6415,7 +6650,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = {}; + var fileDiagnostics = ts.createMap(); var diagnosticsModified = false; var modificationCount = 0; return { @@ -6429,12 +6664,12 @@ var ts; return modificationCount; } function reattachFileDiagnostics(newFile) { - if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) { - return; - } - for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) { - var diagnostic = _a[_i]; - diagnostic.file = newFile; + var diagnostics = fileDiagnostics[newFile.fileName]; + if (diagnostics) { + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + diagnostic.file = newFile; + } } } function add(diagnostic) { @@ -6468,9 +6703,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); } @@ -6481,15 +6714,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", @@ -6502,7 +6733,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" - }; + }); function escapeString(s) { s = escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, getReplacement) : s; return s; @@ -6983,21 +7214,11 @@ var ts; isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 69) { - return true; - } - else if (isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } + 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); @@ -7026,6 +7247,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; @@ -7082,7 +7307,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 @@ -7276,7 +7501,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.parseTime = 0; var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -7399,6 +7623,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); @@ -7677,14 +7903,17 @@ var ts; case 280: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); + 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; @@ -7719,7 +7948,7 @@ var ts; var sourceFile; var parseDiagnostics; var syntaxCursor; - var token; + var currentToken; var sourceText; var nodeCount; var identifiers; @@ -7747,7 +7976,7 @@ var ts; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = {}; + identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; contextFlags = scriptKind === 1 || scriptKind === 2 ? 134217728 : 0; @@ -7769,10 +7998,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; @@ -7936,26 +8165,29 @@ 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 speculationHelper(callback, isLookAhead) { - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var saveContextFlags = contextFlags; @@ -7964,7 +8196,7 @@ var ts; : scanner.tryScan(callback); ts.Debug.assert(saveContextFlags === contextFlags); if (!result || isLookAhead) { - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -7977,20 +8209,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(); } @@ -8005,14 +8237,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; @@ -8022,19 +8254,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; @@ -8076,14 +8308,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(); @@ -8095,18 +8327,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(); @@ -8118,7 +8350,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); @@ -8128,7 +8360,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token === t && tryParse(nextTokenCanFollowModifier); + return token() === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -8138,39 +8370,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); @@ -8181,21 +8413,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) { @@ -8207,23 +8439,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: @@ -8236,7 +8468,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; @@ -8249,11 +8481,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; @@ -8263,7 +8495,7 @@ var ts; return isStartOfExpression(); } function isListTerminator(kind) { - if (token === 1) { + if (token() === 1) { return true; } switch (kind) { @@ -8275,49 +8507,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; @@ -8572,7 +8804,7 @@ var ts; break; } parseExpected(24); - if (considerSemicolonAsDelimiter && token === 23 && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -8617,7 +8849,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); @@ -8642,7 +8874,7 @@ var ts; var span = createNode(197); span.expression = allowInAnd(parseExpression); var literal; - if (token === 16) { + if (token() === 16) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -8652,14 +8884,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); @@ -8685,7 +8914,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); @@ -8722,7 +8951,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token === 25) { + if (token() === 25) { return parseBracketedList(17, parseTypeParameter, 25, 27); } } @@ -8733,7 +8962,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 || token === 97; + return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; } function setModifiers(node, modifiers) { if (modifiers) { @@ -8743,7 +8972,7 @@ var ts; } function parseParameter() { var node = createNode(142); - if (token === 97) { + if (token() === 97) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); @@ -8752,7 +8981,7 @@ var ts; setModifiers(node, 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 && node.flags === 0 && ts.isModifierKind(token())) { nextToken(); } node.questionToken = parseOptionalToken(53); @@ -8810,17 +9039,17 @@ var ts; return 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; @@ -8832,14 +9061,14 @@ 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); @@ -8853,7 +9082,7 @@ 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.name = name; @@ -8868,7 +9097,7 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token === 56) { + if (token() === 56) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); @@ -8877,34 +9106,34 @@ var ts; } 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 || 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(); @@ -8916,7 +9145,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token === 17 || token === 25; + return token() === 17 || token() === 25; } function parseTypeLiteral() { var node = createNode(159); @@ -8956,10 +9185,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: @@ -8970,13 +9208,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 { @@ -8996,7 +9239,7 @@ var ts; } } function isStartOfType() { - switch (token) { + switch (token()) { case 117: case 132: case 130: @@ -9013,7 +9256,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: @@ -9022,7 +9270,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token === 18 || isStartOfParameter() || isStartOfType(); + return token() === 18 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -9036,7 +9284,7 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token === operator) { + if (token() === operator) { var types = [type]; types.pos = type.pos; while (parseOptional(operator)) { @@ -9056,20 +9304,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; @@ -9078,17 +9326,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; } } @@ -9110,7 +9358,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -9122,7 +9370,7 @@ var ts; if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156); } - if (token === 92) { + if (token() === 92) { return parseFunctionOrConstructorType(157); } return parseUnionTypeOrHigher(); @@ -9131,7 +9379,7 @@ var ts; return parseOptional(54) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { - switch (token) { + switch (token()) { case 97: case 95: case 93: @@ -9159,7 +9407,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -9181,10 +9429,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() { @@ -9203,8 +9451,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; } } @@ -9220,7 +9468,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())) { @@ -9229,7 +9477,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token === 114) { + if (token() === 114) { if (inYieldContext()) { return true; } @@ -9245,7 +9493,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); @@ -9255,7 +9503,7 @@ 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); @@ -9286,7 +9534,7 @@ var ts; return undefined; } var isAsync = !!(arrowFunction.flags & 256); - var lastToken = token; + var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 || lastToken === 15) ? parseArrowFunctionExpressionBody(isAsync) @@ -9294,25 +9542,25 @@ var ts; return 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) { @@ -9375,7 +9623,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token === 118) { + if (token() === 118) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -9386,13 +9634,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; } } @@ -9406,18 +9654,18 @@ var ts; 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); @@ -9450,16 +9698,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; } @@ -9475,13 +9723,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: @@ -9536,7 +9784,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -9560,7 +9808,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token === 119) { + if (token() === 119) { if (inAwaitContext()) { return true; } @@ -9575,18 +9823,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); @@ -9598,7 +9843,7 @@ var ts; return simpleUnaryExpression; } function parseSimpleUnaryExpression() { - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -9612,12 +9857,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: @@ -9625,6 +9874,7 @@ var ts; case 78: case 101: case 103: + case 119: return false; case 25: if (sourceFile.languageVariant !== 1) { @@ -9635,29 +9885,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); @@ -9668,7 +9918,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); @@ -9707,7 +9957,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); @@ -9724,11 +9974,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: @@ -9736,7 +9986,7 @@ 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 = []; @@ -9744,11 +9994,11 @@ var ts; 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; } @@ -9764,7 +10014,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token === 27) { + if (token() === 27) { node = createNode(243, fullStart); scanJsxText(); } @@ -9785,7 +10035,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); @@ -9798,7 +10048,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248); parseExpected(15); - if (token !== 16) { + if (token() !== 16) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -9811,14 +10061,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) { + switch (token()) { case 9: node.initializer = parseLiteralNode(); break; @@ -9868,7 +10118,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; @@ -9878,7 +10128,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; @@ -9889,10 +10139,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); @@ -9904,7 +10154,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; @@ -9916,7 +10166,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(); @@ -9945,7 +10195,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token) { + switch (token()) { case 17: case 21: case 18: @@ -9972,7 +10222,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token) { + switch (token()) { case 8: case 9: case 11: @@ -10025,8 +10275,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() { @@ -10063,10 +10313,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; @@ -10129,7 +10379,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); @@ -10202,8 +10452,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 { @@ -10229,11 +10479,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); @@ -10285,7 +10535,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token === 71 ? parseCaseClause() : parseDefaultClause(); + return token() === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213); @@ -10311,8 +10561,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); } @@ -10352,19 +10602,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: @@ -10392,16 +10642,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; @@ -10417,7 +10667,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token) { + switch (token()) { case 55: case 23: case 15: @@ -10465,13 +10715,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: @@ -10543,7 +10793,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token) { + switch (token()) { case 102: case 108: case 74: @@ -10566,7 +10816,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: nextToken(); - switch (token) { + switch (token()) { case 77: case 56: return parseExportAssignment(fullStart, decorators, modifiers); @@ -10587,17 +10837,17 @@ var ts; } 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); @@ -10610,7 +10860,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 { @@ -10636,13 +10886,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(); @@ -10651,14 +10901,14 @@ 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: @@ -10671,7 +10921,7 @@ var ts; ts.Debug.fail(); } nextToken(); - if (token === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -10745,7 +10995,7 @@ var ts; 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 { @@ -10778,31 +11028,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: @@ -10840,8 +11090,8 @@ var ts; 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; } @@ -10867,9 +11117,9 @@ var ts; 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; @@ -10881,7 +11131,7 @@ var ts; return modifiers; } function parseClassElement() { - if (token === 23) { + if (token() === 23) { var result = createNode(198); nextToken(); return finishNode(result); @@ -10893,22 +11143,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_9 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_9, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -10941,7 +11191,7 @@ var ts; : undefined; } function isImplementsClause() { - return token === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { if (isHeritageClause()) { @@ -10950,9 +11200,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); @@ -10962,13 +11212,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); @@ -11044,14 +11294,14 @@ var ts; var node = createNode(225, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - if (token === 137) { + if (token() === 137) { node.name = parseIdentifier(); node.flags |= 131072; } else { node.name = parseLiteralNode(true); } - if (token === 15) { + if (token() === 15) { node.body = parseModuleBlock(); } else { @@ -11061,7 +11311,7 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (token === 137) { + if (token() === 137) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } else if (parseOptional(126)) { @@ -11069,14 +11319,14 @@ var ts; } 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() { @@ -11101,7 +11351,7 @@ 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); @@ -11116,8 +11366,8 @@ var ts; importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || - token === 37 || - token === 15) { + token() === 37 || + token() === 15) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136); } @@ -11132,7 +11382,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); } @@ -11150,7 +11400,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token === 9) { + if (token() === 9) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -11179,14 +11429,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(); @@ -11209,7 +11459,7 @@ var ts; } else { node.exportClause = parseNamedImportsOrExports(237); - if (token === 136 || (token === 9 && !scanner.hasPrecedingLineBreak())) { + if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } @@ -11308,7 +11558,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token) { + switch (token()) { case 37: case 53: case 17: @@ -11321,13 +11571,13 @@ 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); scanner.setText(content, start, length); - token = scanner.scan(); + currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -11345,12 +11595,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; @@ -11361,20 +11611,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(); @@ -11387,7 +11637,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token) { + switch (token()) { case 37: return parseJSDocAllType(); case 53: @@ -11414,7 +11664,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(); } @@ -11445,7 +11703,7 @@ var ts; result.parameters = parseDelimitedList(22, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18); - if (token === 54) { + if (token() === 54) { nextToken(); result.type = parseJSDocType(); } @@ -11462,12 +11720,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; } @@ -11510,7 +11768,7 @@ var ts; function parseJSDocRecordMember() { var result = createNode(266); result.name = parseSimplePropertyName(); - if (token === 54) { + if (token() === 54) { nextToken(); result.type = parseJSDocType(); } @@ -11559,15 +11817,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); } @@ -11587,14 +11850,14 @@ var ts; } 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; @@ -11618,8 +11881,8 @@ var ts; var canParseTag = true; var seenAsterisk = true; nextJSDocToken(); - while (token !== 1) { - switch (token) { + while (token() !== 1) { + switch (token()) { case 55: if (canParseTag) { parseTag(); @@ -11657,12 +11920,12 @@ var ts; return finishNode(result, end); } function skipWhitespace() { - while (token === 5 || token === 4) { + while (token() === 5 || token() === 4) { nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(token === 55); + ts.Debug.assert(token() === 55); var atToken = createNode(55, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -11708,7 +11971,7 @@ var ts; } } function tryParseTypeExpression() { - if (token !== 15) { + if (token() !== 15) { return undefined; } var typeExpression = parseJSDocTypeExpression(); @@ -11727,7 +11990,7 @@ var ts; } parseExpected(20); } - else if (ts.tokenIsIdentifierOrKeyword(token)) { + else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); } if (!name) { @@ -11800,8 +12063,8 @@ var ts; 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_10 = jsDocTypeReference.name; + if (name_10.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -11820,9 +12083,9 @@ 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); @@ -11854,7 +12117,7 @@ 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(); @@ -11887,16 +12150,16 @@ var ts; var typeParameters = []; typeParameters.pos = scanner.getStartPos(); while (true) { - var name_10 = parseJSDocIdentifierName(); - if (!name_10) { + var name_11 = parseJSDocIdentifierName(); + if (!name_11) { 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_11.pos); + typeParameter.name = name_11; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token === 24) { + if (token() === 24) { nextJSDocToken(); } else { @@ -11912,10 +12175,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) { @@ -11995,8 +12258,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } } @@ -12068,8 +12331,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; visitNode(node); } return; @@ -12221,7 +12484,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.bindTime = 0; function getModuleInstanceState(node) { if (node.kind === 222 || node.kind === 223) { return 0; @@ -12259,9 +12521,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() { @@ -12294,7 +12557,7 @@ var ts; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; + classifiableNames = ts.createMap(); symbolCount = 0; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { @@ -12333,10 +12596,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; @@ -12420,35 +12683,38 @@ var ts; var isDefaultExport = node.flags & 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 (declaration.flags & 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; @@ -12466,8 +12732,8 @@ var ts; else { if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192)) { 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; @@ -12484,7 +12750,7 @@ var ts; if (containerFlags & 1) { container = blockScopeContainer = node; if (containerFlags & 32) { - container.locals = {}; + container.locals = ts.createMap(); } addToContainerChain(container); } @@ -12659,15 +12925,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: @@ -12676,9 +12936,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: @@ -12700,10 +12959,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, @@ -12747,7 +13002,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingSwitchStatement(switchStatement)) { + if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -13335,12 +13590,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) { @@ -13379,7 +13634,7 @@ var ts; } default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; + blockScopeContainer.locals = ts.createMap(); addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -13592,7 +13847,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: @@ -13608,7 +13863,7 @@ 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; return; @@ -13650,10 +13905,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: @@ -13702,15 +13957,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) { @@ -13732,7 +13986,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) { @@ -13763,18 +14017,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; @@ -13788,7 +14044,7 @@ var ts; return; } if (!funcSymbol.members) { - funcSymbol.members = {}; + funcSymbol.members = ts.createMap(); } declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } @@ -13818,7 +14074,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; } @@ -13955,7 +14211,6 @@ var ts; return node.id; } ts.getNodeId = getNodeId; - ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -13972,7 +14227,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); @@ -14028,30 +14283,37 @@ var ts; 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 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 enumNumberIndexInfo = createIndexInfo(stringType, true); - var globals = {}; + var globals = ts.createMap(); var patternAmbientModules; var getGlobalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; @@ -14087,10 +14349,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 = []; @@ -14106,7 +14366,7 @@ var ts; var potentialThisCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); - var typeofEQFacts = { + var typeofEQFacts = ts.createMap({ "string": 1, "number": 2, "boolean": 4, @@ -14114,8 +14374,8 @@ var ts; "undefined": 16384, "object": 16, "function": 32 - }; - var typeofNEFacts = { + }); + var typeofNEFacts = ts.createMap({ "string": 128, "number": 256, "boolean": 512, @@ -14123,16 +14383,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", @@ -14142,15 +14402,13 @@ 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 _displayBuilder; - var builtinGlobals = (_a = {}, - _a[undefinedSymbol.name] = undefinedSymbol, - _a - ); + var builtinGlobals = ts.createMap(); + builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -14176,13 +14434,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) @@ -14196,9 +14454,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; @@ -14219,9 +14477,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; } @@ -14241,12 +14499,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); @@ -14262,28 +14520,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]); } } } @@ -14305,7 +14552,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); } @@ -14316,13 +14563,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) { @@ -14337,23 +14582,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; + } + } } } } @@ -14437,7 +14684,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 || @@ -14474,7 +14721,7 @@ var ts; } result = undefined; } - if (ts.hasProperty(moduleExports, name) && + if (moduleExports[name] && moduleExports[name].flags === 8388608 && ts.getDeclarationOfKind(moduleExports[name], 238)) { break; @@ -14503,7 +14750,7 @@ var ts; case 221: case 192: case 222: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { if (lastLocation && lastLocation.flags & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; @@ -14521,7 +14768,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; } @@ -14572,8 +14819,9 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -14601,7 +14849,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); @@ -14630,33 +14878,30 @@ 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 false; + 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 checkResolvedBlockScopedVariable(result, errorLocation) { 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)); } } @@ -14713,7 +14958,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); @@ -14729,9 +14974,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); } } } @@ -14747,25 +14992,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) { + var name_12 = specifier.propertyName || specifier.name; + if (name_12.text) { if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { 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_12.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_12.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_11.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_12.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_12.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_12, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_12)); } return symbol; } @@ -14780,10 +15028,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) { @@ -14804,7 +15052,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."); @@ -14812,6 +15060,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; @@ -14841,6 +15090,7 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); if (node.kind === 235) { checkExpressionCached(node.expression); } @@ -14857,11 +15107,11 @@ 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) { @@ -14873,7 +15123,7 @@ var ts; } var symbol; if (name.kind === 69) { - var message = meaning === 1536 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; @@ -14882,7 +15132,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); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -14940,7 +15190,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(moduleReferenceLiteral, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + } } return undefined; } @@ -14970,7 +15227,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] = { @@ -14978,7 +15235,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]; } @@ -14996,11 +15253,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); @@ -15009,7 +15266,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++) { @@ -15060,8 +15317,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) { @@ -15069,6 +15326,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; @@ -15083,14 +15346,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); } } } @@ -15108,7 +15369,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; @@ -15133,7 +15394,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) { @@ -15150,10 +15411,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)) { @@ -15180,10 +15441,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; } @@ -15226,7 +15487,7 @@ var ts; 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; @@ -15297,10 +15558,10 @@ 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); @@ -15351,6 +15612,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"; @@ -15473,35 +15759,45 @@ var ts; 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) { + 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) { + 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 & 32) { writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } + else if (type.flags & 64) { + writer.writeStringLiteral(type.text); + } else { writePunctuation(writer, 15); writeSpace(writer); @@ -15524,7 +15820,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); @@ -15546,6 +15842,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; @@ -15567,16 +15868,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); } @@ -15593,7 +15894,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); @@ -15995,13 +16296,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) { @@ -16018,7 +16319,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); } @@ -16059,7 +16360,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) { @@ -16101,7 +16402,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); @@ -16138,19 +16439,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_12 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_12)) { + var name_13 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_13)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_12); + var text = getTextOfPropertyName(name_13); 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_13, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_13)); return unknownType; } } @@ -16163,7 +16464,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); @@ -16175,7 +16476,7 @@ 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; @@ -16208,7 +16509,7 @@ 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) { @@ -16243,9 +16544,14 @@ 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); } @@ -16257,26 +16563,24 @@ var ts; 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 checkExpressionCached(element.initializer); } 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; @@ -16287,7 +16591,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; }); @@ -16296,27 +16600,27 @@ 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) { 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 e.kind === 193 ? 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); @@ -16361,14 +16665,21 @@ var ts; if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = undefined; + var type = void 0; if (declaration.kind === 187 || declaration.kind === 172 && declaration.parent.kind === 187) { - type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? + if (declaration.flags & 134217728) { + 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); })); + checkExpressionCached(decl.parent.right); }); + type = getUnionType(declaredTypes, true); } - if (type === undefined) { + else { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { @@ -16460,9 +16771,9 @@ var ts; 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; @@ -16513,7 +16824,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); @@ -16573,7 +16884,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); @@ -16600,7 +16911,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 80896) { + if (baseConstructorType.flags & 2588672) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -16616,25 +16927,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); @@ -16655,7 +16969,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; } @@ -16688,7 +17002,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]; @@ -16720,8 +17034,8 @@ var ts; 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; } @@ -16735,20 +17049,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; } @@ -16761,8 +17075,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); @@ -16773,12 +17088,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; } } @@ -16790,19 +17105,80 @@ 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 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] = createType(256); + memberType.symbol = memberSymbol; + memberType.baseType = enumType; + memberType.text = "" + 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; @@ -16826,11 +17202,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); @@ -16901,7 +17280,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; @@ -16909,7 +17288,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); @@ -16919,7 +17298,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; } } @@ -16936,19 +17315,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); @@ -16958,7 +17345,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); @@ -16984,7 +17371,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; @@ -16994,11 +17381,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); @@ -17022,22 +17409,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]; @@ -17083,7 +17454,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; @@ -17108,7 +17479,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); @@ -17168,7 +17539,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)); } @@ -17182,41 +17553,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; } } } @@ -17227,7 +17593,7 @@ var ts; var prop = _c[_b]; getPropertyOfUnionOrIntersectionType(type, prop.name); } - if (type.flags & 16384) { + if (type.flags & 524288) { break; } } @@ -17235,12 +17601,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); @@ -17248,19 +17614,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; @@ -17268,7 +17634,7 @@ 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]; @@ -17287,7 +17653,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 16384) { + else if (containingType.flags & 524288) { return undefined; } } @@ -17300,11 +17666,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 | @@ -17312,47 +17687,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; } @@ -17362,7 +17736,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; } @@ -17387,7 +17761,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes); + return getUnionType(propTypes, true); } } return undefined; @@ -17470,7 +17844,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; @@ -17490,7 +17864,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) { @@ -17516,6 +17890,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; @@ -17526,7 +17903,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; } @@ -17611,7 +17988,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); @@ -17635,7 +18012,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]; } } @@ -17655,7 +18032,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; @@ -17699,7 +18076,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; } @@ -17731,24 +18108,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; @@ -17758,20 +18138,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; @@ -17821,8 +18210,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; @@ -17831,7 +18221,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793056) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -17857,14 +18247,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) : @@ -17899,7 +18289,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; } @@ -17913,7 +18303,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); @@ -17923,8 +18313,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) { @@ -17952,16 +18342,39 @@ 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) { @@ -17969,30 +18382,68 @@ var ts; } 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) { + if (type.flags & 524288) { + addTypesToUnion(typeSet, type.types); + } + else if (type.flags & 1) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && type.flags & 6144) { + if (type.flags & 2048) typeSet.containsUndefined = true; - if (type.flags & 64) + if (type.flags & 4096) typeSet.containsNull = true; - if (!(type.flags & 2097152)) + if (!(type.flags & 33554432)) typeSet.containsNonWideningType = true; } - else if (type !== neverType && !ts.contains(typeSet, type)) { - typeSet.push(type); + else if (!(type.flags & 8192)) { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(type.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])) { @@ -18010,7 +18461,7 @@ var ts; } } } - function getUnionType(types, noSubtypeReduction) { + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -18018,17 +18469,11 @@ 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); } if (typeSet.length === 0) { @@ -18036,78 +18481,103 @@ var ts; 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, getTypeFromTypeNode), 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, getTypeFromTypeNode), 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 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 = checkExpression(node.literal); } return links.resolvedType; } @@ -18146,7 +18616,7 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node) { + function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { switch (node.kind) { case 117: case 258: @@ -18168,11 +18638,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); @@ -18189,9 +18667,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: @@ -18205,7 +18683,7 @@ var ts; case 281: case 269: case 265: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); case 69: case 139: var symbol = getSymbolAtLocation(node); @@ -18251,6 +18729,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) { @@ -18283,7 +18762,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; @@ -18318,7 +18797,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; @@ -18349,9 +18828,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; } @@ -18403,26 +18884,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; @@ -18465,10 +18943,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; @@ -18479,22 +18957,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); @@ -18607,8 +19088,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; @@ -18634,6 +19115,73 @@ var ts; sourceNonRestParamCount; } } + function isEnumTypeRelatedTo(source, target, errorReporter) { + if (source === target) { + return true; + } + if (source.symbol.name !== target.symbol.name || !(source.symbol.flags & 256) || !(target.symbol.flags & 256)) { + return 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 false; + } + } + } + return 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 | 64) && target.flags & 16) + return true; + if (source.flags & 64 && target.flags & 256 && source.text === target.text) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + 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; @@ -18672,6 +19220,16 @@ 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 === target) @@ -18679,78 +19237,50 @@ var ts; 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 & 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; @@ -18763,14 +19293,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; @@ -18778,22 +19308,25 @@ var ts; } } if (reportErrors) { + if (source.flags & 2588672 && target.flags & 8190) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } 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; @@ -18803,7 +19336,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 || @@ -18812,7 +19345,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)) { @@ -18830,7 +19363,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)) { @@ -18860,14 +19393,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) { @@ -18891,14 +19420,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) { @@ -18970,7 +19495,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = {}; + maybeStack[depth] = ts.createMap(); maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; @@ -19002,7 +19527,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; @@ -19015,7 +19540,7 @@ var ts; } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -19081,7 +19606,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); @@ -19194,7 +19719,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) || @@ -19231,27 +19756,6 @@ 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; @@ -19274,7 +19778,7 @@ 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); @@ -19286,12 +19790,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; @@ -19333,8 +19837,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; @@ -19384,31 +19890,23 @@ 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; - } - return flags; - } function getCommonSupertype(types) { if (!strictNullChecks) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } - 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); + return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -19438,44 +19936,72 @@ 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 isUnitUnionType(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 getBaseTypeOfUnitType(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, getBaseTypeOfUnitType)) : + 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_8 = types; _i < types_8.length; _i++) { + var t = types_8[_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 === emptyStringType ? 32 : 0 : + type.flags & 64 ? type === zeroType ? 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; @@ -19497,7 +20023,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); @@ -19508,7 +20034,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 1048576)) { + if (!(type.flags & 16777216)) { return type; } var regularType = type.regularType; @@ -19518,7 +20044,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; } @@ -19532,31 +20058,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)) { @@ -19564,22 +20087,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))); } @@ -19624,7 +20144,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); } @@ -19666,12 +20186,24 @@ var ts; isFixed: false }; } + 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 inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = {}; + var visited = ts.createMap(); inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -19682,11 +20214,21 @@ 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]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var t = _c[_b]; if (typeIdenticalToSomeType(t, source.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); @@ -19697,8 +20239,8 @@ var ts; 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; @@ -19717,7 +20259,7 @@ var ts; } } } - 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; @@ -19725,20 +20267,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(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -19752,18 +20287,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; } @@ -19771,7 +20304,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (ts.hasProperty(visited, key)) { + if (visited[key]) { return; } visited[key] = true; @@ -19840,8 +20373,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_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -19856,7 +20389,7 @@ 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]; @@ -19868,7 +20401,7 @@ var ts; if (!inferredType) { var inferences = getInferenceCandidates(context, index); if (inferences.length) { - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences, true) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -19934,10 +20467,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: @@ -19949,16 +20478,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; } @@ -19971,6 +20501,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 && + isUnitUnionType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -19997,7 +20561,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++) { @@ -20009,70 +20573,79 @@ 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) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (reducedType !== neverType) { + return reducedType; } } return declaredType; } + function getTypeFactsOfTypes(types) { + var result = 0; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_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 === emptyStringType ? 3030785 : 1982209 : + type === emptyStringType ? 3145473 : 4194049; + } + if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } + if (flags & (64 | 256)) { + var isZero = type === zeroType || type.flags & 256 && 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) { @@ -20166,51 +20739,86 @@ 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 = 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) { return declaredType; @@ -20250,7 +20858,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; } @@ -20269,16 +20877,9 @@ 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)) : + return declaredType.flags & 524288 ? + getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : declaredType; } if (containsMatchingReference(reference, node)) { @@ -20287,37 +20888,55 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var type = getTypeAtFlowNode(flow.antecedent); + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); if (type !== neverType) { var assumeTrue = (flow.flags & 32) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType) { + if (type === neverType && isIncomplete(flowType)) { type = narrowType(declaredType, flow.expression, assumeTrue); } } - 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); } @@ -20326,32 +20945,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) { @@ -20361,26 +21014,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: @@ -20390,23 +21046,34 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + function narrowTypeByEquality(type, operator, value, assumeTrue) { 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 !== neverType ? narrowedType : type; + } + return isUnitType(valueType) ? filterType(type, function (t) { return t !== valueType; }) : 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; @@ -20416,76 +21083,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 === neverType ? 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, t)); }); + return caseType === neverType ? 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; @@ -20498,12 +21129,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) { @@ -20517,23 +21151,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 !== neverType) { + 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, targetType) ? 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); @@ -20541,6 +21174,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) { @@ -20611,20 +21247,48 @@ 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); @@ -20661,16 +21325,22 @@ var ts; 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); + 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 || + flowContainer !== declarationContainer || 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; } @@ -20833,10 +21503,6 @@ var ts; return getInferredClassType(classSymbol); } } - var type = getContextuallyTypedThisType(container); - if (type) { - return type; - } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -20845,7 +21511,7 @@ 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); + return getFlowTypeOfReference(node, type, true, undefined); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -20978,11 +21644,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; @@ -21039,15 +21705,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_14 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_13)) { - var text = getTextOfPropertyName(name_13); + !ts.isBindingPattern(name_14)) { + var text = getTextOfPropertyName(name_14); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -21122,6 +21788,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); } @@ -21141,14 +21810,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_11 = types; _i < types_11.length; _i++) { + var current = types_11[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -21166,7 +21835,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; }); } @@ -21174,7 +21843,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)); @@ -21280,6 +21949,30 @@ var ts; } return undefined; } + function isLiteralTypeLocation(node) { + var parent = node.parent; + switch (parent.kind) { + case 187: + switch (parent.operatorToken.kind) { + case 32: + case 33: + case 30: + case 31: + return true; + } + break; + case 188: + return (node === parent.whenTrue || + node === parent.whenFalse) && + isLiteralTypeLocation(parent); + case 178: + return isLiteralTypeLocation(parent); + case 249: + case 166: + return true; + } + return false; + } function getNonGenericSignature(type) { var signatures = getSignaturesOfStructuredType(type, 0); if (signatures.length === 1) { @@ -21308,13 +22001,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_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -21370,7 +22063,7 @@ var ts; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { - var type = createNewTupleType(elementTypes); + var type = cloneTypeReference(createTupleType(elementTypes)); type.pattern = node; return type; } @@ -21382,7 +22075,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) { @@ -21397,13 +22090,15 @@ 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); @@ -21415,7 +22110,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 { @@ -21431,13 +22126,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 && @@ -21475,7 +22170,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; @@ -21513,7 +22208,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); } @@ -21525,8 +22220,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; } @@ -21580,9 +22275,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) { @@ -21655,7 +22350,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; } @@ -21667,11 +22362,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) { @@ -21694,16 +22389,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; @@ -21756,7 +22451,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; } @@ -21839,7 +22534,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) { @@ -21857,7 +22552,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)); } } @@ -21918,10 +22613,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; } @@ -21930,9 +22625,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); @@ -21953,13 +22648,13 @@ var ts; 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)); + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 268435456 ? apparentType : type)); } return unknownType; } @@ -21978,12 +22673,15 @@ var ts; checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); + if (prop.flags & 8 && isLiteralContextForType(node, propType)) { + propType = getDeclaredTypeOfSymbol(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 isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 @@ -22061,21 +22759,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_15 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_15 !== undefined) { + var prop = getPropertyOfType(objectType, name_15); 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_15, 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; @@ -22120,7 +22819,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)); } @@ -22184,7 +22883,7 @@ var ts; lastParent = parent_9; } lastSymbol = symbol; - if (signature.hasStringLiterals) { + if (signature.hasLiteralTypes) { specializedIndex++; spliceIndex = specializedIndex; cutoffIndex++; @@ -22258,7 +22957,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) { @@ -22358,9 +23057,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)) { @@ -22464,10 +23161,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 { @@ -22708,8 +23405,8 @@ var ts; 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))) { + (isTypeAny(apparentType) && funcType.flags & 16384) || + (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 524288) && isTypeAssignableTo(funcType, globalFunctionType))) { if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } @@ -22782,6 +23479,18 @@ var ts; var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + if (baseTypes.length) { + var baseType = baseTypes[0]; + if (flags & 16 && + baseType.symbol === declaration.parent.symbol) { + return true; + } + } + } if (flags & 8) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } @@ -22799,7 +23508,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 524288) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -22830,7 +23539,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 524288) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); @@ -22930,7 +23639,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return addTypeKind(type, 32); + return includeFalsyTypes(type, 2048); } } return type; @@ -22942,6 +23651,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); @@ -23039,7 +23754,7 @@ var ts; return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); + type = contextualSignature ? getUnionType(types, true) : getCommonSupertype(types); if (!type) { if (funcIsGenerator) { error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); @@ -23047,7 +23762,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types, true)) : getUnionType(types, true); } } if (funcIsGenerator) { @@ -23077,24 +23792,18 @@ 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 (!isUnitUnionType(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)) { @@ -23144,7 +23853,7 @@ 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)) { @@ -23246,7 +23955,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { error(operand, diagnostic); return false; } @@ -23340,16 +24049,22 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (node.operator === 36 && node.operand.kind === 8 && isLiteralContextForType(node, numberType)) { + return 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); @@ -23372,10 +24087,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_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -23387,20 +24102,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_14 = types; _i < types_14.length; _i++) { + var t = types_14[_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_15 = types; _a < types_15.length; _a++) { + var t = types_15[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -23409,13 +24124,13 @@ 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 (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))) { @@ -23424,10 +24139,10 @@ var ts; return booleanType; } function checkInExpression(left, right, leftType, rightType) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 | 132 | 16777216)) { + 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; @@ -23442,14 +24157,14 @@ var ts; } 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_16 = property.name; + if (name_16.kind === 140) { + checkComputedPropertyName(name_16); } - if (isComputedNonLiteralName(name_15)) { + if (isComputedNonLiteralName(name_16)) { return undefined; } - var text = getTextOfPropertyName(name_15); + var text = getTextOfPropertyName(name_16); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -23464,7 +24179,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_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_16)); } } else { @@ -23494,8 +24209,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); @@ -23525,7 +24241,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); @@ -23555,7 +24271,14 @@ var ts; return sourceType; } 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); @@ -23590,15 +24313,15 @@ var ts; case 68: case 46: case 66: - if (leftType.flags & 96) + 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)); } @@ -23612,18 +24335,18 @@ var ts; return numberType; case 35: case 57: - if (leftType.flags & 96) + 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)) { @@ -23655,6 +24378,12 @@ var ts; case 31: case 32: case 33: + var leftIsUnit = isUnitUnionType(leftType); + var rightIsUnit = isUnitUnionType(rightType); + if (!leftIsUnit || !rightIsUnit) { + leftType = leftIsUnit ? getBaseTypeOfUnitType(leftType) : leftType; + rightType = rightIsUnit ? getBaseTypeOfUnitType(rightType) : rightType; + } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -23664,9 +24393,13 @@ 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 : getBaseTypeOfUnitType(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); @@ -23674,8 +24407,8 @@ var ts; 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)); @@ -23760,14 +24493,63 @@ 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 typeContainsLiteralFromEnum(type, enumType) { + if (type.flags & 524288) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 256 && t.baseType === enumType) { + return true; + } + } + } + if (type.flags & 256) { + return type.baseType === enumType; + } + return false; + } + function isLiteralContextForType(node, type) { + if (isLiteralTypeLocation(node)) { + return true; + } + var contextualType = getContextualType(node); + if (contextualType) { + if (contextualType.flags & 16384) { + var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (type === apparentType) { + return true; + } + contextualType = apparentType; + } + if (type.flags & 2) { + return maybeTypeOfKind(contextualType, 32); + } + if (type.flags & 4) { + return maybeTypeOfKind(contextualType, (64 | 256)); + } + if (type.flags & 8) { + return maybeTypeOfKind(contextualType, 128) && !isTypeAssignableTo(booleanType, contextualType); + } + if (type.flags & 16) { + return typeContainsLiteralFromEnum(contextualType, type); + } + } + return false; + } + function checkLiteralExpression(node) { + if (node.kind === 8) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9: + return isLiteralContextForType(node, stringType) ? getLiteralTypeForText(32, node.text) : stringType; + case 8: + return isLiteralContextForType(node, numberType) ? getLiteralTypeForText(64, node.text) : numberType; + case 99: + case 84: + return isLiteralContextForType(node, booleanType) ? node.kind === 99 ? trueType : falseType : booleanType; } - return stringType; } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -23840,10 +24622,6 @@ var ts; } return type; } - function checkNumericLiteral(node) { - checkGrammarNumericLiteral(node); - return numberType; - } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69: @@ -23854,15 +24632,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: @@ -24007,9 +24783,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_17 = _a[_i].name; + if (ts.isBindingPattern(name_17) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_17, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -24037,15 +24813,15 @@ var ts; } 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 name_18 = _a[_i].name; + if (name_18.kind === 69 && + name_18.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_18.kind === 168 || + name_18.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_18, predicateVariableNode, predicateVariableName)) { return true; } } @@ -24099,16 +24875,15 @@ var ts; } } 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); } } } @@ -24119,21 +24894,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)); } @@ -24147,7 +24922,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) { @@ -24161,7 +24936,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); } @@ -24303,12 +25078,7 @@ var ts; 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 (!(node.flags & 65536)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -24330,7 +25100,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) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } } if (node.parent.kind !== 171) { checkSourceElement(node.body); @@ -24383,6 +25156,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) { @@ -24652,10 +25428,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; } @@ -24678,7 +25454,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]; @@ -24704,7 +25480,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; @@ -24715,13 +25491,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); @@ -24826,7 +25602,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); @@ -24982,22 +25758,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) && - !parameterIsThisKeyword(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) { @@ -25025,7 +25799,7 @@ var ts; 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); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -25053,14 +25827,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); } } } @@ -25194,8 +25966,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_19 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_19, name_19); } } } @@ -25265,8 +26037,8 @@ var ts; } 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)); + var name_20 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_20)); if (parent_11.initializer && property && getParentOfSymbol(property)) { checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); } @@ -25442,7 +26214,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 { @@ -25450,7 +26222,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); @@ -25503,7 +26275,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 { @@ -25518,7 +26290,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; @@ -25529,7 +26301,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 { @@ -25544,7 +26316,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; } @@ -25564,7 +26336,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) || @@ -25573,10 +26345,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; @@ -25601,10 +26373,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; } @@ -25616,7 +26388,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)) { @@ -25747,7 +26519,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); @@ -25772,7 +26544,7 @@ 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]; @@ -25787,7 +26559,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]; } @@ -25809,7 +26581,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]; } @@ -25917,6 +26689,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; })) { @@ -25930,15 +26707,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 { @@ -26062,7 +26839,7 @@ 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++) { @@ -26070,11 +26847,11 @@ var ts; 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)) { + 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; @@ -26112,7 +26889,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); @@ -26435,9 +27212,6 @@ var ts; } } } - if (compilerOptions.noImplicitAny && !node.body) { - reportImplicitAnyError(node, anyType); - } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -26463,9 +27237,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_21 = node.name; + if (ts.isBindingPattern(name_21)) { + for (var _b = 0, _c = name_21.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -26491,19 +27265,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); @@ -26531,8 +27306,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 : @@ -26586,11 +27361,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); } } @@ -26634,7 +27409,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); } @@ -26690,13 +27465,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); @@ -26866,9 +27641,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); @@ -26939,7 +27715,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = {}; + var symbols = ts.createMap(); var memberFlags = 0; if (isInsideWithStatementBody(location)) { return []; @@ -26970,7 +27746,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: @@ -26991,7 +27767,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; } } @@ -27079,15 +27855,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; @@ -27095,13 +27869,13 @@ 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); @@ -27132,7 +27906,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) { @@ -27224,7 +27998,7 @@ 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)) { @@ -27305,7 +28079,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; } }); @@ -27315,9 +28089,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_21 = symbol.name; + var name_22 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_21); + var symbol = getPropertyOfType(t, name_22); if (symbol) { symbols_3.push(symbol); } @@ -27350,7 +28124,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) { @@ -27494,7 +28268,7 @@ 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); @@ -27502,7 +28276,7 @@ var ts; if (constructorType && isConstructorType(constructorType)) { return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } - var typeSymbol = resolveEntityName(typeName, 793056, true); + var typeSymbol = resolveEntityName(typeName, 793064, true); if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; } @@ -27513,22 +28287,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 16)) { + else if (isTypeOfKind(type, 1024)) { return ts.TypeReferenceSerializationKind.VoidType; } - 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)) { @@ -27563,7 +28337,7 @@ 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 || @@ -27580,9 +28354,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; @@ -27626,7 +28397,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; } @@ -27732,7 +28503,7 @@ 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"); }); @@ -27752,7 +28523,7 @@ 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; } @@ -27766,7 +28537,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 = []; @@ -27794,49 +28565,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; @@ -28029,6 +28760,56 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } + 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) { if (languageVersion < 2) { return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); @@ -28261,16 +29042,16 @@ 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; + var name_23 = prop.name; if (prop.kind === 193 || - name_22.kind === 140) { - checkGrammarComputedPropertyName(name_22); + name_23.kind === 140) { + checkGrammarComputedPropertyName(name_23); } 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) }; @@ -28283,8 +29064,8 @@ var ts; 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_23.kind === 8) { + checkGrammarNumericLiteral(name_23); } currentKind = Property; } @@ -28300,28 +29081,28 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_22); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_23); if (effectiveName === undefined) { return "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_23, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_23)); } 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 { value: grammarErrorOnNode(name_23, 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 { value: grammarErrorOnNode(name_23, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } }; @@ -28332,19 +29113,19 @@ var ts; } } 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_24 = jsxAttr.name; + if (!seen[name_24.text]) { + seen[name_24.text] = true; } else { - return grammarErrorOnNode(name_23, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_24, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -28668,6 +29449,7 @@ var ts; node.kind === 229 || node.kind === 236 || node.kind === 235 || + node.kind === 228 || (node.flags & 2) || (node.flags & (1 | 512))) { return false; @@ -28719,7 +29501,6 @@ var ts; return true; } } - var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -28753,6 +29534,7 @@ var ts; ts.getNullSourceMapWriter = getNullSourceMapWriter; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var sourceMapDir; var stopOverridingSpan = false; @@ -28881,6 +29663,9 @@ var ts; if (pos === -1) { return; } + if (extendedDiagnostics) { + ts.performance.mark("beforeSourcemap"); + } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); sourceLinePos.line++; sourceLinePos.character++; @@ -28908,6 +29693,10 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); + if (extendedDiagnostics) { + ts.performance.mark("afterSourcemap"); + ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); + } } function getStartPos(range) { var rangeHasDecorators = !!range.decorators; @@ -29085,9 +29874,7 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { - referencesOutput += "/// " + newLine; - } + referencesOutput += "/// " + newLine; } } return { @@ -29176,11 +29963,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; } } @@ -29332,7 +30119,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) { @@ -29401,15 +30188,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_25 = baseName + "_" + count; + if (!(name_25 in currentIdentifiers)) { + return name_25; } } } @@ -29824,7 +30611,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) { @@ -29922,7 +30709,8 @@ 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) { @@ -30458,7 +31246,7 @@ var ts; return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - var entities = { + var entities = ts.createMap({ "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -30712,7 +31500,7 @@ var ts; "clubs": 0x2663, "hearts": 0x2665, "diams": 0x2666 - }; + }); function emitFiles(resolver, host, targetSourceFile) { 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};"; @@ -30738,7 +31526,7 @@ var ts; }; 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 in node.locals) { if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { return false; } @@ -30749,13 +31537,13 @@ var ts; function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = {}; + state.labeledNonLocalBreaks = ts.createMap(); } state.labeledNonLocalBreaks[labelText] = labelMarker; } else { if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = {}; + state.labeledNonLocalContinues = ts.createMap(); } state.labeledNonLocalContinues[labelText] = labelMarker; } @@ -30813,26 +31601,26 @@ var ts; var isOwnFileEmit; var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = (_a = {}, + var moduleEmitDelegates = ts.createMap((_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 = {}, + )); + var bundleEmitDelegates = ts.createMap((_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 = {}; + generatedNameSet = ts.createMap(); nodeToGeneratedName = []; decoratedClassAliases = []; isOwnFileEmit = !isBundledEmit; @@ -30891,24 +31679,24 @@ var ts; } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentFileIdentifiers, name) && - !ts.hasProperty(generatedNameSet, name); + !(name in currentFileIdentifiers) && + !(name in generatedNameSet); } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_25 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_25)) { + var name_26 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_26)) { tempFlags |= flags; - return name_25; + return name_26; } } 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; + var name_27 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_27)) { + return name_27; } } } @@ -31606,8 +32394,8 @@ var ts; } 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); + var name_28 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_28); if (languageVersion === 0 && identifier === "default") { write('["default"]'); } @@ -31674,8 +32462,8 @@ var ts; function emitIdentifier(node) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_28 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_28); + var name_29 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_29); return; } } @@ -31789,6 +32577,10 @@ var ts; else if (node.parent.kind === 188 && node.parent.condition === node) { return true; } + else if (node.parent.kind === 185 || node.parent.kind === 181 || + node.parent.kind === 182 || node.parent.kind === 183) { + return true; + } return false; } function needsParenthesisForPropertyAccessOrInvocation(node) { @@ -32127,9 +32919,9 @@ var ts; 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); + var name_30 = ts.createSynthesizedNode(9); + name_30.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_30); return; } emit(node.expression); @@ -32375,6 +33167,7 @@ var ts; operand.kind !== 181 && operand.kind !== 186 && operand.kind !== 175 && + !(operand.kind === 187 && node.expression.kind === 195) && !(operand.kind === 174 && node.parent.kind === 175) && !(operand.kind === 179 && node.parent.kind === 174) && !(operand.kind === 8 && node.parent.kind === 172)) { @@ -32416,7 +33209,7 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); + return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 @@ -32877,12 +33670,12 @@ var ts; for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { var id = _d[_c]; if (!seen) { - seen = {}; + seen = ts.createMap(); } else { write(", "); } - if (!ts.hasProperty(seen, id.text)) { + if (!(id.text in seen)) { emit(id); seen[id.text] = id.text; } @@ -33335,7 +34128,7 @@ var ts; } if (convertedLoopState) { if (!convertedLoopState.labels) { - convertedLoopState.labels = {}; + convertedLoopState.labels = ts.createMap(); } convertedLoopState.labels[node.label.text] = node.label.text; } @@ -33433,7 +34226,7 @@ var ts; if (modulekind === ts.ModuleKind.System) { return; } - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + if (!exportEquals && exportSpecifiers && name.text in exportSpecifiers) { for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { var specifier = _b[_a]; writeLine(); @@ -33802,12 +34595,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_30 = createTempVariable(0); + var name_31 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_30); - emit(name_30); + tempParameters.push(name_31); + emit(name_31); } else { emit(node.name); @@ -33866,11 +34659,12 @@ var ts; } function emitRestParameter(node) { if (languageVersion < 2 && ts.hasDeclaredRestParameter(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; + var restParam = node.parameters[node.parameters.length - 1]; if (ts.isBindingPattern(restParam.name)) { return; } + var skipThisCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; + var restIndex = node.parameters.length - 1 - skipThisCount; var tempName = createTempVariable(268435456).text; writeLine(); emitLeadingComments(restParam); @@ -33983,7 +34777,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; + var skipCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; var omitCount = languageVersion < 2 && ts.hasDeclaredRestParameter(node) ? 1 : 0; emitList(parameters, skipCount, parameters.length - omitCount - skipCount, false, false); } @@ -34400,12 +35194,7 @@ var ts; emitSignatureParameters(ctor); } else { - if (baseTypeElement) { - write("(...args)"); - } - else { - write("()"); - } + write("()"); } } var startIndex = 0; @@ -34437,7 +35226,7 @@ var ts; write("_super.apply(this, arguments);"); } else { - write("super(...args);"); + write("super(...arguments);"); } emitEnd(baseTypeElement); } @@ -34515,7 +35304,7 @@ var ts; var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192; var generatedName; if (isClassExpressionWithStaticProperties) { - generatedName = getGeneratedNameForNode(node.name); + generatedName = node.name ? getGeneratedNameForNode(node.name) : makeUniqueName("classExpression"); var synthesizedNode = ts.createSynthesizedNode(69); synthesizedNode.text = generatedName; recordTempDeclaration(synthesizedNode); @@ -34965,10 +35754,11 @@ var ts; } if (valueDeclaration) { var parameters = valueDeclaration.parameters; + var skipThisCount = parameters.length && parameters[0].name.originalKeywordKind === 97 ? 1 : 0; var parameterCount = parameters.length; - if (parameterCount > 0) { - for (var i = 0; i < parameterCount; i++) { - if (i > 0) { + if (parameterCount > skipThisCount) { + for (var i = skipThisCount; i < parameterCount; i++) { + if (i > skipThisCount) { write(", "); } if (parameters[i].dotDotDotToken) { @@ -35223,7 +36013,7 @@ var ts; } } function tryRenameExternalModule(moduleName) { - if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { + if (renamedDependencies && moduleName.text in renamedDependencies) { return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; @@ -35523,7 +36313,7 @@ var ts; } function collectExternalModuleInfo(sourceFile) { externalImports = []; - exportSpecifiers = {}; + exportSpecifiers = ts.createMap(); exportEquals = undefined; hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { @@ -35555,8 +36345,8 @@ var ts; 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); + var name_32 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_32] || (exportSpecifiers[name_32] = [])).push(specifier); } } break; @@ -35594,9 +36384,9 @@ var ts; } function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { if (emitRelativePathAsModuleName) { - var name_32 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_32) { - return "\"" + name_32 + "\""; + var name_33 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_33) { + return "\"" + name_33 + "\""; } } var moduleName = ts.getExternalModuleName(importNode); @@ -35635,7 +36425,7 @@ var ts; if (!hasExportStarsToExportValues) { return undefined; } - if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { + if (!exportedDeclarations && !ts.someProperties(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; @@ -35739,15 +36529,15 @@ var ts; if (hoistedVars) { writeLine(); write("var "); - var seen = {}; + var seen = ts.createMap(); for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_33 = local.kind === 69 + var name_34 = local.kind === 69 ? local : local.name; - if (name_33) { - var text = ts.unescapeIdentifier(name_33.text); - if (ts.hasProperty(seen, text)) { + if (name_34) { + var text = ts.unescapeIdentifier(name_34.text); + if (text in seen) { continue; } else { @@ -35825,15 +36615,15 @@ var ts; } if (node.kind === 218 || node.kind === 169) { if (shouldHoistVariable(node, false)) { - var name_34 = node.name; - if (name_34.kind === 69) { + var name_35 = node.name; + if (name_35.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_34); + hoistedVars.push(name_35); } else { - ts.forEachChild(name_34, visit); + ts.forEachChild(name_35, visit); } } return; @@ -35990,7 +36780,7 @@ var ts; write("System.register("); writeModuleName(node, emitRelativePathAsModuleName); write("["); - var groupIndices = {}; + var groupIndices = ts.createMap(); var dependencyGroups = []; for (var i = 0; i < externalImports.length; i++) { var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); @@ -35998,7 +36788,7 @@ var ts; continue; } var key = text.substr(1, text.length - 2); - if (ts.hasProperty(groupIndices, key)) { + if (key in groupIndices) { var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); continue; @@ -36739,11 +37529,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.programTime = 0; - ts.emitTime = 0; - ts.ioReadTime = 0; - ts.ioWriteTime = 0; - ts.version = "2.1.0"; + ts.version = "2.0.2"; var emptyArray = []; var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { @@ -36826,43 +37612,26 @@ var ts; 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") { @@ -36874,6 +37643,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) { @@ -37096,7 +37874,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); @@ -37220,9 +37998,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); @@ -37230,39 +38008,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) { @@ -37270,7 +38046,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; } @@ -37289,6 +38067,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); @@ -37361,14 +38142,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(); } @@ -37376,9 +38151,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) { @@ -37391,7 +38167,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)) { @@ -37410,11 +38186,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 && @@ -37432,7 +38208,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); @@ -37440,7 +38216,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) { @@ -37481,8 +38258,8 @@ var ts; 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]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; if (diagnostic.file) { var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; var fileName = diagnostic.file.fileName; @@ -37523,25 +38300,17 @@ var ts; return []; } var resolutions = []; - var cache = {}; + var cache = ts.createMap(); 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 name_36 = names_1[_i]; + var result = name_36 in cache + ? cache[name_36] + : cache[name_36] = loader(name_36, 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; } @@ -37552,7 +38321,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)); + } + } } } } @@ -37567,13 +38344,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 maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; var currentNodeModulesDepth = 0; - var modulesWithElidedImports = {}; - var sourceFilesFoundSearchingNodeModules = {}; - var start = new Date().getTime(); + var modulesWithElidedImports = ts.createMap(); + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -37600,10 +38377,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]); @@ -37647,7 +38423,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") { @@ -37666,10 +38443,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; @@ -37692,7 +38469,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); @@ -37782,7 +38559,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 }; @@ -37819,9 +38596,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) { @@ -37960,16 +38738,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) { @@ -38013,8 +38791,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; @@ -38201,7 +38979,7 @@ 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(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) { + if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { sourceFilesFoundSearchingNodeModules[file_1.path] = false; if (!options.noResolve) { processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); @@ -38210,7 +38988,7 @@ var ts; modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } - else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { + else if (file_1 && modulesWithElidedImports[file_1.path]) { if (currentNodeModulesDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); @@ -38262,13 +39040,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) { @@ -38285,7 +39064,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; } @@ -38319,7 +39098,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++) { @@ -38411,6 +39190,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; @@ -38456,7 +39238,7 @@ 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)); @@ -38467,17 +39249,17 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.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 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.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 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } if (options.outDir || @@ -39175,10 +39957,10 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_36 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_36); + for (var name_37 in nameToDeclarations) { + var declarations = nameToDeclarations[name_37]; if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_37); if (!matches) { continue; } @@ -39189,14 +39971,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_36); + matches = patternMatcher.getMatches(containers, name_37); 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_37, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -39442,9 +40224,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_38 = decl.name; + if (ts.isBindingPattern(name_38)) { + addChildrenRecursively(name_38); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { addChildrenRecursively(decl.initializer); @@ -39505,14 +40287,14 @@ var ts; } } 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; @@ -39740,7 +40522,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, @@ -39751,7 +40533,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, @@ -39771,46 +40553,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); @@ -39878,7 +40620,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); @@ -39921,7 +40663,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!ts.hasProperty(stringToWordSpans, word)) { + if (!(word in stringToWordSpans)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -40315,7 +41057,7 @@ 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]; @@ -40759,7 +41501,7 @@ var ts; 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) { + if (c.kind === 286 && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -40911,8 +41653,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && - (previousToken.kind === 9 || previousToken.kind === 166)) { + if (previousToken && previousToken.kind === 9) { var start = previousToken.getStart(); var end = previousToken.getEnd(); if (start < position && position < end) { @@ -41061,7 +41802,6 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 - || kind === 166 || kind === 10 || ts.isTemplateLiteralKind(kind)) { return true; @@ -41341,12 +42081,31 @@ var ts; if (host && host.getScriptKind) { scriptKind = host.getScriptKind(fileName); } - if (!scriptKind || scriptKind === 0) { + 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_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; + diagnostic.start = diagnostic.start - 1; + } + return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + } + ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -41356,20 +42115,14 @@ var ts; ; var safeList; function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { - var inferredTypings = {}; + 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); }); - if (result.config) { - safeList = result.config; - } - else { - safeList = {}; - } - ; + safeList = ts.createMap(result.config); } var filesToWatch = []; var searchDirs = []; @@ -41392,7 +42145,7 @@ var ts; } getTypingNamesFromSourceFileNames(fileNames); for (var name_39 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + if (name_39 in inferredTypings && !inferredTypings[name_39]) { inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } @@ -41417,7 +42170,7 @@ var ts; } for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { var typing = typingNames_1[_i]; - if (!ts.hasProperty(inferredTypings, typing)) { + if (!(typing in inferredTypings)) { inferredTypings[typing] = undefined; } } @@ -41428,16 +42181,16 @@ var ts; var jsonConfig = result.config; filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { - mergeTypings(ts.getKeys(jsonConfig.dependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } if (jsonConfig.devDependencies) { - mergeTypings(ts.getKeys(jsonConfig.devDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); } if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); } if (jsonConfig.peerDependencies) { - mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); } } } @@ -41449,7 +42202,7 @@ var ts; mergeTypings(cleanedTypingNames); } else { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); + 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) { @@ -41954,7 +42707,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)); @@ -41985,6 +42738,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, @@ -42011,6 +42769,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, @@ -42038,8 +42798,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)); @@ -42065,10 +42825,10 @@ 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)); } @@ -42243,12 +43003,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); }; @@ -43956,7 +44725,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(282, nodes.pos, nodes.end, 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++) { @@ -43979,13 +44748,16 @@ var 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) { @@ -44410,7 +45182,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; }; @@ -44467,7 +45239,7 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = {}; + var result = ts.createMap(); ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { @@ -44478,13 +45250,13 @@ var ts; } } 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_3 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_3 !== undefined) { + return result_3; } if (declaration.name.kind === 140) { var expr = declaration.name.expression; @@ -44661,6 +45433,7 @@ var ts; ScriptElementKind.interfaceElement = "interface"; ScriptElementKind.typeElement = "type"; ScriptElementKind.enumElement = "enum"; + ScriptElementKind.enumMemberElement = "const"; ScriptElementKind.variableElement = "var"; ScriptElementKind.localVariableElement = "local var"; ScriptElementKind.functionElement = "function"; @@ -44854,7 +45627,7 @@ var ts; 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"; }); + return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); var _loop_3 = function(opt) { @@ -44866,7 +45639,7 @@ var ts; options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); } else { - if (!ts.forEachValue(opt.type, function (v) { return v === value; })) { + if (!ts.forEachProperty(opt.type, function (v) { return v === value; })) { diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); } } @@ -44900,7 +45673,9 @@ var ts; if (transpileOptions.moduleName) { sourceFile.moduleName = transpileOptions.moduleName; } - sourceFile.renamedDependencies = transpileOptions.renamedDependencies; + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMap(transpileOptions.renamedDependencies); + } var newLine = ts.getNewLineCharacter(options); var outputText; var sourceMapText; @@ -44990,13 +45765,13 @@ var ts; ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { if (currentDirectory === void 0) { currentDirectory = ""; } - var buckets = {}; + 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 = ts.lookUp(buckets, key); + var bucket = buckets[key]; if (!bucket && createIfMissing) { buckets[key] = bucket = ts.createFileMap(); } @@ -45004,7 +45779,7 @@ var ts; } 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 entries = buckets[name]; var sourceFiles = []; entries.forEachValue(function (key, entry) { sourceFiles.push({ @@ -45534,7 +46309,10 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 225: return ScriptElementKind.moduleElement; + case 256: + return ts.isExternalModule(node) ? ScriptElementKind.moduleElement : ScriptElementKind.scriptElement; + case 225: + return ScriptElementKind.moduleElement; case 221: case 192: return ScriptElementKind.classElement; @@ -45542,11 +46320,10 @@ var ts; 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; + return getKindOfVariableDeclaration(node); + case 169: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 180: case 220: case 179: return ScriptElementKind.functionElement; @@ -45563,7 +46340,7 @@ var ts; case 151: return ScriptElementKind.callSignatureElement; case 148: return ScriptElementKind.constructorImplementationElement; case 141: return ScriptElementKind.typeParameterElement; - case 255: return ScriptElementKind.variableElement; + case 255: return ScriptElementKind.enumMemberElement; case 142: return (node.flags & 92) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; case 229: case 234: @@ -45571,8 +46348,18 @@ var ts; case 238: case 232: return ScriptElementKind.alias; + case 279: + return ScriptElementKind.typeElement; + default: + return ScriptElementKind.unknown; + } + function getKindOfVariableDeclaration(v) { + return ts.isConst(v) + ? ScriptElementKind.constElement + : ts.isLet(v) + ? ScriptElementKind.letElement + : ScriptElementKind.variableElement; } - return ScriptElementKind.unknown; } ts.getNodeKind = getNodeKind; var CancellationTokenObject = (function () { @@ -45637,14 +46424,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, @@ -45656,7 +46445,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) { @@ -45688,7 +46476,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); } } @@ -45706,7 +46494,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); @@ -45774,7 +46562,7 @@ var ts; var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); if (displayName) { var firstCharCode = displayName.charCodeAt(0); - if ((symbol.flags & 1536) && (firstCharCode === 39 || firstCharCode === 34)) { + if ((symbol.flags & 1920) && (firstCharCode === 39 || firstCharCode === 34)) { return undefined; } } @@ -45800,12 +46588,12 @@ var ts; var sourceFile = getValidSourceFile(fileName); var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var isJsDocTagName = false; - var start = new Date().getTime(); + var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); - log("getCompletionData: Get current token: " + (new Date().getTime() - start)); - start = new Date().getTime(); + log("getCompletionData: Get current token: " + (ts.timestamp() - start)); + start = ts.timestamp(); var insideComment = isInsideComment(sourceFile, currentToken, position); - log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); + log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64) { isJsDocTagName = true; @@ -45835,14 +46623,14 @@ var ts; return undefined; } } - start = new Date().getTime(); + start = ts.timestamp(); var previousToken = ts.findPrecedingToken(position, sourceFile); - log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); + log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); var contextToken = previousToken; if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_5 = new Date().getTime(); + var start_2 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); } var node = currentToken; var isRightOfDot = false; @@ -45879,7 +46667,7 @@ var ts; } } } - var semanticStart = new Date().getTime(); + var semanticStart = ts.timestamp(); var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -45911,7 +46699,7 @@ var ts; return undefined; } } - log("getCompletionData: Semantic work: " + (new Date().getTime() - semanticStart)); + 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; @@ -45941,7 +46729,7 @@ var ts; symbols.push(symbol); } } - if (isJavaScriptFile && type.flags & 16384) { + if (isJavaScriptFile && type.flags & 524288) { var unionType = type; for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { var elementType = _c[_b]; @@ -45981,7 +46769,7 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - var symbolMeanings = 793056 | 107455 | 1536 | 8388608; + var symbolMeanings = 793064 | 107455 | 1920 | 8388608; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); return true; } @@ -45993,12 +46781,12 @@ var ts; return scope; } function isCompletionListBlocker(contextToken) { - var start = new Date().getTime(); + var start = ts.timestamp(); var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || isSolelyIdentifierDefinitionLocation(contextToken) || isDotOfNumericLiteral(contextToken) || isInJsxText(contextToken); - log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); return result; } function isInJsxText(contextToken) { @@ -46066,12 +46854,11 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 - || contextToken.kind === 166 || contextToken.kind === 10 || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_6 = contextToken.getStart(); + var start_3 = contextToken.getStart(); var end = contextToken.getEnd(); - if (start_6 < position && position < end) { + if (start_3 < position && position < end) { return true; } if (position === end) { @@ -46088,6 +46875,7 @@ var ts; if (objectLikeContainer.kind === 171) { isNewIdentifierLocation = true; typeForObject = typeChecker.getContextualType(objectLikeContainer); + typeForObject = typeForObject && typeForObject.getNonNullableType(); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 167) { @@ -46317,7 +47105,7 @@ var ts; return false; } function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = {}; + 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()) { @@ -46326,16 +47114,16 @@ var ts; var name_41 = element.propertyName || element.name; existingImportsOrExports[name_41.text] = true; } - if (ts.isEmpty(existingImportsOrExports)) { + if (!ts.someProperties(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); }); + 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 = {}; + 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 && @@ -46358,10 +47146,10 @@ var ts; } existingMemberNames[existingName] = true; } - return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames[m.name]; }); } function filterJsxAttributes(symbols, attributes) { - var seenNames = {}; + 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()) { @@ -46371,7 +47159,7 @@ var ts; seenNames[attr.name.text] = true; } } - return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); + return ts.filter(symbols, function (a) { return !seenNames[a.name]; }); } } function getCompletionsAtPosition(fileName, position) { @@ -46414,7 +47202,7 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var target = program.getCompilerOptions().target; @@ -46462,22 +47250,22 @@ var ts; }; } function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { - var start = new Date().getTime(); - var uniqueNames = {}; + 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 (!ts.lookUp(uniqueNames, id)) { + if (!uniqueNames[id]) { entries.push(entry); uniqueNames[id] = id; } } } } - log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniqueNames; } function getStringLiteralCompletionEntries(sourceFile, position) { @@ -46485,18 +47273,32 @@ var ts; if (!node || node.kind !== 9) { return undefined; } - var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo); + 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 { + var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); + if (argumentInfo) { + return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node); + } return getStringLiteralCompletionEntriesFromContextualType(node); } } - function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element) { + var typeChecker = program.getTypeChecker(); + 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 typeChecker = program.getTypeChecker(); var candidates = []; var entries = []; @@ -46541,11 +47343,11 @@ var ts; if (!type) { return; } - if (type.flags & 16384) { + if (type.flags & 524288) { ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); } else { - if (type.flags & 256) { + if (type.flags & 32) { result.push({ name: type.text, kindModifiers: ScriptElementKindModifier.none, @@ -46744,7 +47546,7 @@ var ts; displayParts.push(ts.keywordPart(92)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 65536) && type.symbol) { + if (!(type.flags & 2097152) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); } addSignatureDisplayParts(signature, allSignatures, 8); @@ -46805,7 +47607,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(56)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512)); } if (symbolFlags & 384) { addNewLineIfDisplayPartsExist(); @@ -46879,7 +47681,14 @@ var ts; } if (symbolFlags & 8388608) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(89)); + 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) { @@ -46950,6 +47759,24 @@ var ts; } 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 = program.getTypeChecker().getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(); + if (documentation.length > 0) { + break; + } + } + } + } } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; function addNewLineIfDisplayPartsExist() { @@ -47146,7 +47973,7 @@ var ts; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { - var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); + var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; if (referenceFile && referenceFile.resolvedFileName) { return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } @@ -47203,14 +48030,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 16384) { - var result_3 = []; + if (type.flags & 524288 && !(type.flags & 16)) { + var result_4 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_3, getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(result_4, getDefinitionFromSymbol(t.symbol, node)); } }); - return result_3; + return result_4; } if (!type.symbol) { return undefined; @@ -47258,14 +48085,14 @@ var ts; if (!referencedSymbols) { return undefined; } - var fileNameToDocumentHighlights = {}; + var fileNameToDocumentHighlights = ts.createMap(); 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); + var documentHighlights = fileNameToDocumentHighlights[fileName_1]; if (!documentHighlights) { documentHighlights = { fileName: fileName_1, highlightSpans: [] }; fileNameToDocumentHighlights[fileName_1] = documentHighlights; @@ -47834,7 +48661,7 @@ var ts; var sourceFile = sourceFiles_4[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName) !== undefined) { + if (nameTable[internedName] !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -48272,7 +49099,7 @@ var ts; result.push(rootSymbol); } if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, {}); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, ts.createMap()); } }); return result; @@ -48281,7 +49108,7 @@ var ts; if (!symbol) { return; } - if (ts.hasProperty(previousIterationSymbolsCache, symbol.name)) { + if (symbol.name in previousIterationSymbolsCache) { return; } if (symbol.flags & (32 | 64)) { @@ -48340,9 +49167,9 @@ var ts; 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; }); + var result_5 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_5, ts.createMap()); + return ts.forEach(result_5, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -48362,20 +49189,20 @@ var ts; 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); + var result_6 = []; + var symbol_2 = contextualType.getProperty(name); + if (symbol_2) { + result_6.push(symbol_2); } - if (contextualType.flags & 16384) { + if (contextualType.flags & 524288) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -48590,7 +49417,6 @@ var ts; case 172: case 139: case 9: - case 166: case 84: case 99: case 93: @@ -48891,6 +49717,9 @@ var ts; } } function tryClassifyNode(node) { + if (ts.isJSDocTag(node)) { + return true; + } if (ts.nodeIsMissing(node)) { return true; } @@ -48965,7 +49794,7 @@ var ts; else if (tokenKind === 8) { return 4; } - else if (tokenKind === 9 || tokenKind === 166) { + else if (tokenKind === 9) { return token.parent.kind === 246 ? 24 : 6; } else if (tokenKind === 10) { @@ -49077,12 +49906,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) { @@ -49268,7 +50097,7 @@ var ts; function getStringLiteralTypeForNode(node, typeChecker) { var searchNode = node.parent.kind === 166 ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 256) { + if (type && type.flags & 32) { return type; } return undefined; @@ -49410,7 +50239,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = {}; + var nameTable = ts.createMap(); walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -49478,7 +50307,7 @@ var ts; 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 length_4 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -49486,8 +50315,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } - entries.push({ length: length_3, classification: convertClassification(type) }); - lastEnd = start + length_3; + entries.push({ length: length_4, classification: convertClassification(type) }); + lastEnd = start + length_4; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -49623,7 +50452,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9 || token === 166) { + if (token === 9) { var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { var lastCharIndex = tokenText.length - 1; @@ -49753,7 +50582,6 @@ var ts; case 8: return 4; case 9: - case 166: return 6; case 10: return 7; @@ -49923,7 +50751,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 }; @@ -50059,18 +50887,24 @@ var ts; return { responseRequired: false }; }, _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) { @@ -50834,7 +51668,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; @@ -50965,18 +51799,21 @@ 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); + var resolution = newResolutions[name_43]; if (!resolution) { - var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_43); + var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_43]; if (moduleResolutionIsValid(existingResolution)) { resolution = existingResolution; } @@ -51164,7 +52001,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) { @@ -51248,7 +52085,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); @@ -51293,7 +52130,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) { @@ -51327,15 +52164,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 () { @@ -51383,7 +52220,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())) { @@ -51391,14 +52229,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++) { @@ -51415,8 +52265,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"; } @@ -51486,13 +52339,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 } }); } } } @@ -51512,7 +52365,7 @@ 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); } @@ -51720,12 +52573,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)) { @@ -51790,7 +52643,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 { @@ -51804,14 +52657,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; @@ -51819,13 +52673,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); @@ -51889,30 +52743,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) { @@ -51934,45 +52783,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; @@ -51981,22 +52829,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); @@ -52010,7 +52858,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); }); @@ -52049,6 +52897,7 @@ var ts; project.setProjectOptions(projectOptions); project.finishGraph(); } + return errors; } }; ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { @@ -53229,7 +54078,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; }); }; @@ -53240,7 +54089,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); }); }; } } @@ -53327,7 +54176,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; @@ -53377,6 +54226,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; @@ -53384,11 +54236,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; @@ -53715,6 +54567,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; @@ -53838,4 +54697,4 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "1.9"; +var toolsVersion = "2.0"; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 1821c212574..7fe9da64cfe 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,8 +304,12 @@ declare namespace ts { JSDocTypedefTag = 279, JSDocPropertyTag = 280, JSDocTypeLiteral = 281, - SyntaxList = 282, - Count = 283, + JSDocLiteralType = 282, + JSDocNullKeyword = 283, + JSDocUndefinedKeyword = 284, + JSDocNeverKeyword = 285, + SyntaxList = 286, + Count = 287, FirstAssignment = 56, LastAssignment = 68, FirstReservedWord = 70, @@ -327,9 +334,9 @@ declare namespace ts { LastBinaryOperator = 68, FirstNode = 139, FirstJSDocNode = 257, - LastJSDocNode = 281, + LastJSDocNode = 282, FirstJSDocTagNode = 273, - LastJSDocTagNode = 281, + LastJSDocTagNode = 285, } const enum NodeFlags { None = 0, @@ -595,8 +602,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; @@ -705,11 +713,16 @@ declare namespace ts { properties: NodeArray; 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; @@ -1022,6 +1035,9 @@ 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; @@ -1100,6 +1116,11 @@ declare namespace ts { clauseEnd: number; antecedent: FlowNode; } + type FlowType = Type | IncompleteType; + interface IncompleteType { + flags: TypeFlags; + type: Type; + } interface AmdDependency { path: string; name: string; @@ -1297,6 +1318,7 @@ declare namespace ts { InElementType = 64, UseFullyQualifiedType = 128, InFirstTypeArgument = 256, + InTypeAlias = 512, } const enum SymbolFormatFlags { None = 0, @@ -1364,7 +1386,7 @@ declare namespace ts { 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; + isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; getReferencedValueDeclaration(reference: Identifier): Declaration; getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind; @@ -1372,7 +1394,7 @@ declare namespace ts { 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[]; } const enum SymbolFlags { @@ -1411,18 +1433,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, @@ -1430,8 +1452,8 @@ declare namespace ts { MethodExcludes = 99263, GetAccessorExcludes = 41919, SetAccessorExcludes = 74687, - TypeParameterExcludes = 530912, - TypeAliasExcludes = 793056, + TypeParameterExcludes = 530920, + TypeAliasExcludes = 793064, AliasExcludes = 8388608, ModuleMember = 8914931, ExportHasLocal = 944, @@ -1458,6 +1480,8 @@ declare namespace ts { exportSymbol?: Symbol; constEnumOnlyModule?: boolean; isReferenced?: boolean; + isReplaceableByMethod?: boolean; + isAssigned?: boolean; } interface SymbolLinks { target?: Symbol; @@ -1469,6 +1493,8 @@ declare namespace ts { mapper?: TypeMapper; referenced?: boolean; containingType?: UnionOrIntersectionType; + hasCommonType?: boolean; + isDiscriminantProperty?: boolean; resolvedExports?: SymbolTable; exportsChecked?: boolean; isDeclarationWithCollidingName?: boolean; @@ -1477,9 +1503,7 @@ declare namespace ts { } interface TransientSymbol extends Symbol, SymbolLinks { } - interface SymbolTable { - [index: string]: Symbol; - } + type SymbolTable = Map; interface Pattern { prefix: string; suffix: string; @@ -1506,13 +1530,14 @@ declare namespace ts { ClassWithBodyScopedClassBinding = 524288, BodyScopedClassBinding = 1048576, NeedsLoopOutParameter = 2097152, + AssignmentsMarked = 4194304, } interface NodeLinks { + flags?: NodeCheckFlags; resolvedType?: Type; resolvedSignature?: Signature; resolvedSymbol?: Symbol; resolvedIndexInfo?: IndexInfo; - flags?: NodeCheckFlags; enumMemberValue?: number; isVisible?: boolean; hasReportedStatementInAmbientContext?: boolean; @@ -1527,42 +1552,50 @@ 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, + FreshObjectLiteral = 16777216, + ContainsWideningType = 33554432, + ContainsObjectLiteral = 67108864, + ContainsAnyFunctionType = 134217728, + ThisType = 268435456, + ObjectLiteralPatternWithComputedProperties = 536870912, + Nullable = 6144, + Literal = 480, + 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 { @@ -1570,13 +1603,21 @@ 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; } + interface EnumType extends Type { + memberTypes: Map; + } + interface EnumLiteralType extends LiteralType { + baseType: EnumType & UnionType; + } interface ObjectType extends Type { } interface InterfaceType extends ObjectType { @@ -1601,13 +1642,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 { } @@ -1650,7 +1688,7 @@ declare namespace ts { resolvedReturnType: Type; minArgumentCount: number; hasRestParameter: boolean; - hasStringLiterals: boolean; + hasLiteralTypes: boolean; target?: Signature; mapper?: TypeMapper; unionSignatures?: Signature[]; @@ -1670,6 +1708,7 @@ declare namespace ts { interface TypeMapper { (t: TypeParameter): Type; mappedTypes?: Type[]; + targetTypes?: Type[]; instantiations?: Type[]; context?: InferenceContext; } @@ -1723,7 +1762,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 { @@ -1738,6 +1777,7 @@ declare namespace ts { declaration?: boolean; declarationDir?: string; diagnostics?: boolean; + extendedDiagnostics?: boolean; disableSizeLimit?: boolean; emitBOM?: boolean; emitDecoratorMetadata?: boolean; @@ -1863,7 +1903,7 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; - wildcardDirectories?: Map; + wildcardDirectories?: MapLike; } const enum WatchDirectoryFlags { None = 0, @@ -1871,7 +1911,7 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - wildcardDirectories: Map; + wildcardDirectories: MapLike; } interface CommandLineOptionBase { name: string; @@ -2030,6 +2070,7 @@ declare namespace ts { directoryExists?(directoryName: string): boolean; realpath?(path: string): string; getCurrentDirectory?(): string; + getDirectories?(path: string): string[]; } interface ResolvedModule { resolvedFileName: string; @@ -2081,12 +2122,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 { @@ -2094,12 +2148,15 @@ 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 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 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 concatenate(array1: T[], array2: T[]): T[]; @@ -2113,18 +2170,20 @@ declare namespace ts { 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 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 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 cloneMap(map: Map): Map; + function clone(object: T): T; + function extend(first: T1, second: T2): T1 & T2; function isArray(value: any): value is any[]; function memoize(callback: () => T): () => T; let localizedDiagnosticMessages: Map; @@ -2178,6 +2237,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; @@ -2192,7 +2252,8 @@ 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 { @@ -4896,6 +4957,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; @@ -5178,6 +5245,24 @@ 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; + }; Import_declaration_0_is_using_private_name_1: { code: number; category: DiagnosticCategory; @@ -5598,7 +5683,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; @@ -5766,6 +5851,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; @@ -6486,6 +6577,12 @@ declare namespace ts { key: string; message: string; }; + Property_0_is_declared_but_never_used: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Variable_0_implicitly_has_an_1_type: { code: number; category: DiagnosticCategory; @@ -6862,9 +6959,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): { @@ -6875,6 +6973,9 @@ declare namespace ts { config?: any; error?: Diagnostic; }; + function generateTSConfig(options: CompilerOptions, fileNames: string[]): { + compilerOptions: Map; + }; function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; @@ -6913,7 +7014,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; @@ -6933,6 +7033,7 @@ declare namespace ts { 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; @@ -6988,7 +7089,7 @@ declare namespace ts { function getSuperContainer(node: Node, stopOnFunctions: boolean): Node; function getImmediatelyInvokedFunctionExpression(func: Node): CallExpression; function isSuperPropertyOrElementAccess(node: Node): boolean; - function getEntityNameFromTypeNode(node: TypeNode): EntityName | Expression; + function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression; function getInvokedExpression(node: CallLikeExpression): Expression; function nodeCanBeDecorated(node: Node): boolean; function nodeIsDecorated(node: Node): boolean; @@ -7032,6 +7133,7 @@ declare namespace ts { 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; @@ -7115,12 +7217,13 @@ declare namespace ts { function isLeftHandSideExpression(expr: Expression): boolean; function isAssignmentOperator(token: SyntaxKind): boolean; function isExpressionWithTypeArgumentsInClassExtendsClause(node: Node): boolean; - function isSupportedExpressionWithTypeArguments(node: ExpressionWithTypeArguments): 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; @@ -7151,7 +7254,6 @@ declare namespace ts { function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; } 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; @@ -7167,7 +7269,6 @@ declare namespace ts { }; } declare namespace ts { - let bindTime: number; const enum ModuleInstanceState { NonInstantiated = 0, Instantiated = 1, @@ -7178,7 +7279,6 @@ declare namespace ts { } declare namespace ts { function getNodeId(node: Node): number; - let checkTime: number; function getSymbolId(symbol: Symbol): number; function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker; } @@ -7208,10 +7308,6 @@ 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; function resolveTripleslashReference(moduleName: string, containingFile: string): string; @@ -7226,7 +7322,6 @@ 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 { @@ -7236,7 +7331,7 @@ declare namespace ts { } 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 { @@ -7353,6 +7448,10 @@ 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.JsTyping { interface TypingResolutionHost { @@ -7586,6 +7685,11 @@ declare namespace ts.formatting { SpaceAfterOpenBraceInJsxExpression: Rule; NoSpaceBeforeCloseBraceInJsxExpression: Rule; SpaceBeforeCloseBraceInJsxExpression: Rule; + SpaceBeforeJsxAttribute: Rule; + SpaceBeforeSlashInJsxOpeningElement: Rule; + NoSpaceBeforeGreaterThanTokenInJsxOpeningElement: Rule; + NoSpaceBeforeEqualInJsxAttribute: Rule; + NoSpaceAfterEqualInJsxAttribute: Rule; constructor(); static IsForContext(context: FormattingContext): boolean; static IsNotForContext(context: FormattingContext): boolean; @@ -7613,8 +7717,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; @@ -7819,7 +7926,7 @@ declare namespace ts { interface IScriptSnapshot { getText(start: number, end: number): string; getLength(): number; - getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined; dispose?(): void; } namespace ScriptSnapshot { @@ -8164,6 +8271,7 @@ declare namespace ts { const interfaceElement: string; const typeElement: string; const enumElement: string; + const enumMemberElement: string; const variableElement: string; const localVariableElement: string; const functionElement: string; @@ -8255,7 +8363,7 @@ declare namespace ts { fileName?: string; reportDiagnostics?: boolean; moduleName?: string; - renamedDependencies?: Map; + renamedDependencies?: MapLike; } interface TranspileOutput { outputText: string; @@ -8328,7 +8436,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; @@ -8460,12 +8568,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; @@ -8474,7 +8582,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); @@ -8504,8 +8612,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; @@ -8514,15 +8636,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); @@ -8532,6 +8654,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; @@ -8566,15 +8689,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; @@ -8621,7 +8742,7 @@ declare namespace ts.server { class TextChange { pos: number; deleteLen: number; - insertedText?: string; + insertedText: string; constructor(pos: number, deleteLen: number, insertedText?: string); getTextChangeRange(): TextChangeRange; } @@ -8747,11 +8868,16 @@ declare namespace ts { 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; @@ -8810,6 +8936,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; @@ -8850,6 +8977,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; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 8823d9ce98b..e9b95951e62 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -69,8 +69,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 +163,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 +196,31 @@ var ts; return undefined; } ts.forEach = forEach; - function contains(array, value, areEqual) { + 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; } } @@ -170,19 +262,43 @@ 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_3 = array; _i < array_3.length; _i++) { + var item = array_3[_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++) { @@ -219,11 +335,15 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + loop: 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); + 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; @@ -333,96 +453,117 @@ 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 isEmpty(map) { - for (var id in map) { - if (hasProperty(map, id)) { - return false; + 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 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.isEmpty = isEmpty; + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + var result = createMap(); + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var value = array_8[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToMap = arrayToMap; + 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; - 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)); - } - } - } - return result; - } - ts.reduceProperties = reduceProperties; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -444,9 +585,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) { @@ -855,10 +994,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++) { @@ -881,7 +1025,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += "(/.+?)?"; + subpattern += doubleAsteriskRegexFragment; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -893,6 +1037,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; } @@ -913,8 +1067,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); @@ -1013,6 +1173,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) { @@ -1075,9 +1236,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"; } @@ -1286,13 +1451,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(); @@ -1301,23 +1466,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]; - } + (fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback); } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -1329,8 +1489,9 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); + var callbacks = fileWatcherCallbacks[filePath]; + if (callbacks) { + var newCallbacks = ts.copyListRemovingItem(callback, callbacks); if (newCallbacks.length === 0) { delete fileWatcherCallbacks[filePath]; } @@ -1343,7 +1504,7 @@ var ts; 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); @@ -2037,6 +2198,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." }, @@ -2084,6 +2246,9 @@ 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." }, 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}'." }, @@ -2154,7 +2319,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}'." }, @@ -2182,6 +2347,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." }, @@ -2302,6 +2468,7 @@ var ts; 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." }, 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." }, @@ -2361,7 +2528,7 @@ var ts; return token >= 69; } ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; - var textToToken = { + var textToToken = ts.createMap({ "abstract": 115, "any": 117, "as": 116, @@ -2485,7 +2652,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,]; @@ -2526,9 +2693,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; } @@ -3869,6 +4034,10 @@ var ts; name: "diagnostics", type: "boolean" }, + { + name: "extendedDiagnostics", + type: "boolean" + }, { name: "emitBOM", type: "boolean" @@ -3899,10 +4068,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 }, @@ -3929,7 +4098,7 @@ var ts; { name: "module", shortName: "m", - type: { + type: ts.createMap({ "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -3937,16 +4106,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 }, @@ -3964,6 +4133,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", @@ -4087,12 +4260,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 }, @@ -4121,10 +4294,10 @@ 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 }, { @@ -4225,7 +4398,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", @@ -4247,7 +4420,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 }, @@ -4283,13 +4456,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) { @@ -4302,16 +4481,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 { @@ -4360,10 +4539,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)); @@ -4464,6 +4643,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); @@ -4481,7 +4730,6 @@ var ts; } return output; } - var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -4556,7 +4804,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; } @@ -4573,7 +4821,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); } @@ -4608,7 +4856,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 { @@ -4629,8 +4877,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); } @@ -4652,12 +4900,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; } } @@ -4692,20 +4937,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) { @@ -4715,12 +4960,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]; } } } @@ -4733,7 +4976,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; } } @@ -4808,24 +5051,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; @@ -4843,7 +5068,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -4852,14 +5077,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; } @@ -4878,7 +5103,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; @@ -4978,16 +5203,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); @@ -5370,9 +5599,9 @@ 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; } } @@ -5601,6 +5830,7 @@ var ts; case 155: return node.typeName; case 194: + ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69: case 139: @@ -5962,8 +6192,8 @@ var ts; var tag = _b[_a]; if (tag.kind === 275) { var parameterTag = tag; - var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_7.text === parameterName) { + var name_8 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_8.text === parameterName) { return parameterTag; } } @@ -6030,7 +6260,7 @@ 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; @@ -6077,6 +6307,7 @@ var ts; case 146: case 225: case 232: + case 228: case 142: case 253: case 145: @@ -6193,9 +6424,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; @@ -6415,7 +6650,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = {}; + var fileDiagnostics = ts.createMap(); var diagnosticsModified = false; var modificationCount = 0; return { @@ -6429,12 +6664,12 @@ var ts; return modificationCount; } function reattachFileDiagnostics(newFile) { - if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) { - return; - } - for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) { - var diagnostic = _a[_i]; - diagnostic.file = newFile; + var diagnostics = fileDiagnostics[newFile.fileName]; + if (diagnostics) { + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + diagnostic.file = newFile; + } } } function add(diagnostic) { @@ -6468,9 +6703,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); } @@ -6481,15 +6714,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", @@ -6502,7 +6733,7 @@ var ts; "\u2028": "\\u2028", "\u2029": "\\u2029", "\u0085": "\\u0085" - }; + }); function escapeString(s) { s = escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, getReplacement) : s; return s; @@ -6983,21 +7214,11 @@ var ts; isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 69) { - return true; - } - else if (isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } + 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); @@ -7026,6 +7247,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; @@ -7082,7 +7307,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 @@ -7276,7 +7501,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.parseTime = 0; var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -7399,6 +7623,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); @@ -7677,14 +7903,17 @@ var ts; case 280: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); + 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; @@ -7719,7 +7948,7 @@ var ts; var sourceFile; var parseDiagnostics; var syntaxCursor; - var token; + var currentToken; var sourceText; var nodeCount; var identifiers; @@ -7747,7 +7976,7 @@ var ts; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = {}; + identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; contextFlags = scriptKind === 1 || scriptKind === 2 ? 134217728 : 0; @@ -7769,10 +7998,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; @@ -7936,26 +8165,29 @@ 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 speculationHelper(callback, isLookAhead) { - var saveToken = token; + var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var saveContextFlags = contextFlags; @@ -7964,7 +8196,7 @@ var ts; : scanner.tryScan(callback); ts.Debug.assert(saveContextFlags === contextFlags); if (!result || isLookAhead) { - token = saveToken; + currentToken = saveToken; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; } @@ -7977,20 +8209,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(); } @@ -8005,14 +8237,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; @@ -8022,19 +8254,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; @@ -8076,14 +8308,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(); @@ -8095,18 +8327,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(); @@ -8118,7 +8350,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); @@ -8128,7 +8360,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token === t && tryParse(nextTokenCanFollowModifier); + return token() === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -8138,39 +8370,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); @@ -8181,21 +8413,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) { @@ -8207,23 +8439,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: @@ -8236,7 +8468,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; @@ -8249,11 +8481,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; @@ -8263,7 +8495,7 @@ var ts; return isStartOfExpression(); } function isListTerminator(kind) { - if (token === 1) { + if (token() === 1) { return true; } switch (kind) { @@ -8275,49 +8507,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; @@ -8572,7 +8804,7 @@ var ts; break; } parseExpected(24); - if (considerSemicolonAsDelimiter && token === 23 && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token() === 23 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -8617,7 +8849,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); @@ -8642,7 +8874,7 @@ var ts; var span = createNode(197); span.expression = allowInAnd(parseExpression); var literal; - if (token === 16) { + if (token() === 16) { reScanTemplateToken(); literal = parseTemplateLiteralFragment(); } @@ -8652,14 +8884,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); @@ -8685,7 +8914,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); @@ -8722,7 +8951,7 @@ var ts; return finishNode(node); } function parseTypeParameters() { - if (token === 25) { + if (token() === 25) { return parseBracketedList(17, parseTypeParameter, 25, 27); } } @@ -8733,7 +8962,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 || token === 97; + return token() === 22 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 || token() === 97; } function setModifiers(node, modifiers) { if (modifiers) { @@ -8743,7 +8972,7 @@ var ts; } function parseParameter() { var node = createNode(142); - if (token === 97) { + if (token() === 97) { node.name = createIdentifier(true, undefined); node.type = parseParameterType(); return finishNode(node); @@ -8752,7 +8981,7 @@ var ts; setModifiers(node, 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 && node.flags === 0 && ts.isModifierKind(token())) { nextToken(); } node.questionToken = parseOptionalToken(53); @@ -8810,17 +9039,17 @@ var ts; return 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; @@ -8832,14 +9061,14 @@ 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); @@ -8853,7 +9082,7 @@ 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.name = name; @@ -8868,7 +9097,7 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - if (token === 56) { + if (token() === 56) { property.initializer = parseNonParameterInitializer(); } parseTypeMemberSemicolon(); @@ -8877,34 +9106,34 @@ var ts; } 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 || 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(); @@ -8916,7 +9145,7 @@ var ts; } function isStartOfConstructSignature() { nextToken(); - return token === 17 || token === 25; + return token() === 17 || token() === 25; } function parseTypeLiteral() { var node = createNode(159); @@ -8956,10 +9185,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: @@ -8970,13 +9208,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 { @@ -8996,7 +9239,7 @@ var ts; } } function isStartOfType() { - switch (token) { + switch (token()) { case 117: case 132: case 130: @@ -9013,7 +9256,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: @@ -9022,7 +9270,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token === 18 || isStartOfParameter() || isStartOfType(); + return token() === 18 || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -9036,7 +9284,7 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token === operator) { + if (token() === operator) { var types = [type]; types.pos = type.pos; while (parseOptional(operator)) { @@ -9056,20 +9304,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; @@ -9078,17 +9326,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; } } @@ -9110,7 +9358,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token === 124 && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -9122,7 +9370,7 @@ var ts; if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156); } - if (token === 92) { + if (token() === 92) { return parseFunctionOrConstructorType(157); } return parseUnionTypeOrHigher(); @@ -9131,7 +9379,7 @@ var ts; return parseOptional(54) ? parseType() : undefined; } function isStartOfLeftHandSideExpression() { - switch (token) { + switch (token()) { case 97: case 95: case 93: @@ -9159,7 +9407,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -9181,10 +9429,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() { @@ -9203,8 +9451,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; } } @@ -9220,7 +9468,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())) { @@ -9229,7 +9477,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token === 114) { + if (token() === 114) { if (inYieldContext()) { return true; } @@ -9245,7 +9493,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); @@ -9255,7 +9503,7 @@ 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); @@ -9286,7 +9534,7 @@ var ts; return undefined; } var isAsync = !!(arrowFunction.flags & 256); - var lastToken = token; + var lastToken = token(); arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 || lastToken === 15) ? parseArrowFunctionExpressionBody(isAsync) @@ -9294,25 +9542,25 @@ var ts; return 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) { @@ -9375,7 +9623,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function tryParseAsyncSimpleArrowFunctionExpression() { - if (token === 118) { + if (token() === 118) { var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); if (isUnParenthesizedAsyncArrowFunction === 1) { var asyncModifier = parseModifiersForArrowFunction(); @@ -9386,13 +9634,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; } } @@ -9406,18 +9654,18 @@ var ts; 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); @@ -9450,16 +9698,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; } @@ -9475,13 +9723,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: @@ -9536,7 +9784,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -9560,7 +9808,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token === 119) { + if (token() === 119) { if (inAwaitContext()) { return true; } @@ -9575,18 +9823,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); @@ -9598,7 +9843,7 @@ var ts; return simpleUnaryExpression; } function parseSimpleUnaryExpression() { - switch (token) { + switch (token()) { case 35: case 36: case 50: @@ -9612,12 +9857,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: @@ -9625,6 +9874,7 @@ var ts; case 78: case 101: case 103: + case 119: return false; case 25: if (sourceFile.languageVariant !== 1) { @@ -9635,29 +9885,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); @@ -9668,7 +9918,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); @@ -9707,7 +9957,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); @@ -9724,11 +9974,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: @@ -9736,7 +9986,7 @@ 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 = []; @@ -9744,11 +9994,11 @@ var ts; 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; } @@ -9764,7 +10014,7 @@ var ts; var tagName = parseJsxElementName(); var attributes = parseList(13, parseJsxAttribute); var node; - if (token === 27) { + if (token() === 27) { node = createNode(243, fullStart); scanJsxText(); } @@ -9785,7 +10035,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); @@ -9798,7 +10048,7 @@ var ts; function parseJsxExpression(inExpressionContext) { var node = createNode(248); parseExpected(15); - if (token !== 16) { + if (token() !== 16) { node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { @@ -9811,14 +10061,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) { + switch (token()) { case 9: node.initializer = parseLiteralNode(); break; @@ -9868,7 +10118,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; @@ -9878,7 +10128,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; @@ -9889,10 +10139,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); @@ -9904,7 +10154,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; @@ -9916,7 +10166,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(); @@ -9945,7 +10195,7 @@ var ts; : undefined; } function canFollowTypeArgumentsInExpression() { - switch (token) { + switch (token()) { case 17: case 21: case 18: @@ -9972,7 +10222,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token) { + switch (token()) { case 8: case 9: case 11: @@ -10025,8 +10275,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() { @@ -10063,10 +10313,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; @@ -10129,7 +10379,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); @@ -10202,8 +10452,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 { @@ -10229,11 +10479,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); @@ -10285,7 +10535,7 @@ var ts; return finishNode(node); } function parseCaseOrDefaultClause() { - return token === 71 ? parseCaseClause() : parseDefaultClause(); + return token() === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { var node = createNode(213); @@ -10311,8 +10561,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); } @@ -10352,19 +10602,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: @@ -10392,16 +10642,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; @@ -10417,7 +10667,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token) { + switch (token()) { case 55: case 23: case 15: @@ -10465,13 +10715,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: @@ -10543,7 +10793,7 @@ var ts; var fullStart = getNodePos(); var decorators = parseDecorators(); var modifiers = parseModifiers(); - switch (token) { + switch (token()) { case 102: case 108: case 74: @@ -10566,7 +10816,7 @@ var ts; return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); case 82: nextToken(); - switch (token) { + switch (token()) { case 77: case 56: return parseExportAssignment(fullStart, decorators, modifiers); @@ -10587,17 +10837,17 @@ var ts; } 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); @@ -10610,7 +10860,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 { @@ -10636,13 +10886,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(); @@ -10651,14 +10901,14 @@ 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: @@ -10671,7 +10921,7 @@ var ts; ts.Debug.fail(); } nextToken(); - if (token === 138 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 138 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -10745,7 +10995,7 @@ var ts; 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 { @@ -10778,31 +11028,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: @@ -10840,8 +11090,8 @@ var ts; 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; } @@ -10867,9 +11117,9 @@ var ts; 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; @@ -10881,7 +11131,7 @@ var ts; return modifiers; } function parseClassElement() { - if (token === 23) { + if (token() === 23) { var result = createNode(198); nextToken(); return finishNode(result); @@ -10893,22 +11143,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_9 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_9, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -10941,7 +11191,7 @@ var ts; : undefined; } function isImplementsClause() { - return token === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 106 && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses(isClassHeritageClause) { if (isHeritageClause()) { @@ -10950,9 +11200,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); @@ -10962,13 +11212,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); @@ -11044,14 +11294,14 @@ var ts; var node = createNode(225, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - if (token === 137) { + if (token() === 137) { node.name = parseIdentifier(); node.flags |= 131072; } else { node.name = parseLiteralNode(true); } - if (token === 15) { + if (token() === 15) { node.body = parseModuleBlock(); } else { @@ -11061,7 +11311,7 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (token === 137) { + if (token() === 137) { return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } else if (parseOptional(126)) { @@ -11069,14 +11319,14 @@ var ts; } 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() { @@ -11101,7 +11351,7 @@ 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); @@ -11116,8 +11366,8 @@ var ts; importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || - token === 37 || - token === 15) { + token() === 37 || + token() === 15) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); parseExpected(136); } @@ -11132,7 +11382,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); } @@ -11150,7 +11400,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token === 9) { + if (token() === 9) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -11179,14 +11429,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(); @@ -11209,7 +11459,7 @@ var ts; } else { node.exportClause = parseNamedImportsOrExports(237); - if (token === 136 || (token === 9 && !scanner.hasPrecedingLineBreak())) { + if (token() === 136 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { parseExpected(136); node.moduleSpecifier = parseModuleSpecifier(); } @@ -11308,7 +11558,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token) { + switch (token()) { case 37: case 53: case 17: @@ -11321,13 +11571,13 @@ 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); scanner.setText(content, start, length); - token = scanner.scan(); + currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -11345,12 +11595,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; @@ -11361,20 +11611,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(); @@ -11387,7 +11637,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token) { + switch (token()) { case 37: return parseJSDocAllType(); case 53: @@ -11414,7 +11664,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(); } @@ -11445,7 +11703,7 @@ var ts; result.parameters = parseDelimitedList(22, parseJSDocParameter); checkForTrailingComma(result.parameters); parseExpected(18); - if (token === 54) { + if (token() === 54) { nextToken(); result.type = parseJSDocType(); } @@ -11462,12 +11720,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; } @@ -11510,7 +11768,7 @@ var ts; function parseJSDocRecordMember() { var result = createNode(266); result.name = parseSimplePropertyName(); - if (token === 54) { + if (token() === 54) { nextToken(); result.type = parseJSDocType(); } @@ -11559,15 +11817,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); } @@ -11587,14 +11850,14 @@ var ts; } 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; @@ -11618,8 +11881,8 @@ var ts; var canParseTag = true; var seenAsterisk = true; nextJSDocToken(); - while (token !== 1) { - switch (token) { + while (token() !== 1) { + switch (token()) { case 55: if (canParseTag) { parseTag(); @@ -11657,12 +11920,12 @@ var ts; return finishNode(result, end); } function skipWhitespace() { - while (token === 5 || token === 4) { + while (token() === 5 || token() === 4) { nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(token === 55); + ts.Debug.assert(token() === 55); var atToken = createNode(55, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -11708,7 +11971,7 @@ var ts; } } function tryParseTypeExpression() { - if (token !== 15) { + if (token() !== 15) { return undefined; } var typeExpression = parseJSDocTypeExpression(); @@ -11727,7 +11990,7 @@ var ts; } parseExpected(20); } - else if (ts.tokenIsIdentifierOrKeyword(token)) { + else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); } if (!name) { @@ -11800,8 +12063,8 @@ var ts; 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_10 = jsDocTypeReference.name; + if (name_10.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -11820,9 +12083,9 @@ 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); @@ -11854,7 +12117,7 @@ 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(); @@ -11887,16 +12150,16 @@ var ts; var typeParameters = []; typeParameters.pos = scanner.getStartPos(); while (true) { - var name_10 = parseJSDocIdentifierName(); - if (!name_10) { + var name_11 = parseJSDocIdentifierName(); + if (!name_11) { 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_11.pos); + typeParameter.name = name_11; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token === 24) { + if (token() === 24) { nextJSDocToken(); } else { @@ -11912,10 +12175,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) { @@ -11995,8 +12258,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } } @@ -12068,8 +12331,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; visitNode(node); } return; @@ -12221,7 +12484,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.bindTime = 0; function getModuleInstanceState(node) { if (node.kind === 222 || node.kind === 223) { return 0; @@ -12259,9 +12521,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() { @@ -12294,7 +12557,7 @@ var ts; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; + classifiableNames = ts.createMap(); symbolCount = 0; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { @@ -12333,10 +12596,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; @@ -12420,35 +12683,38 @@ var ts; var isDefaultExport = node.flags & 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 (declaration.flags & 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; @@ -12466,8 +12732,8 @@ var ts; else { if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192)) { 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; @@ -12484,7 +12750,7 @@ var ts; if (containerFlags & 1) { container = blockScopeContainer = node; if (containerFlags & 32) { - container.locals = {}; + container.locals = ts.createMap(); } addToContainerChain(container); } @@ -12659,15 +12925,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: @@ -12676,9 +12936,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: @@ -12700,10 +12959,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, @@ -12747,7 +13002,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingSwitchStatement(switchStatement)) { + if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -13335,12 +13590,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) { @@ -13379,7 +13634,7 @@ var ts; } default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; + blockScopeContainer.locals = ts.createMap(); addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -13592,7 +13847,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: @@ -13608,7 +13863,7 @@ 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; return; @@ -13650,10 +13905,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: @@ -13702,15 +13957,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) { @@ -13732,7 +13986,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) { @@ -13763,18 +14017,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; @@ -13788,7 +14044,7 @@ var ts; return; } if (!funcSymbol.members) { - funcSymbol.members = {}; + funcSymbol.members = ts.createMap(); } declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } @@ -13818,7 +14074,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; } @@ -13955,7 +14211,6 @@ var ts; return node.id; } ts.getNodeId = getNodeId; - ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -13972,7 +14227,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); @@ -14028,30 +14283,37 @@ var ts; 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 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 enumNumberIndexInfo = createIndexInfo(stringType, true); - var globals = {}; + var globals = ts.createMap(); var patternAmbientModules; var getGlobalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; @@ -14087,10 +14349,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 = []; @@ -14106,7 +14366,7 @@ var ts; var potentialThisCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); - var typeofEQFacts = { + var typeofEQFacts = ts.createMap({ "string": 1, "number": 2, "boolean": 4, @@ -14114,8 +14374,8 @@ var ts; "undefined": 16384, "object": 16, "function": 32 - }; - var typeofNEFacts = { + }); + var typeofNEFacts = ts.createMap({ "string": 128, "number": 256, "boolean": 512, @@ -14123,16 +14383,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", @@ -14142,15 +14402,13 @@ 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 _displayBuilder; - var builtinGlobals = (_a = {}, - _a[undefinedSymbol.name] = undefinedSymbol, - _a - ); + var builtinGlobals = ts.createMap(); + builtinGlobals[undefinedSymbol.name] = undefinedSymbol; initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -14176,13 +14434,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) @@ -14196,9 +14454,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; @@ -14219,9 +14477,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; } @@ -14241,12 +14499,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); @@ -14262,28 +14520,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]); } } } @@ -14305,7 +14552,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); } @@ -14316,13 +14563,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) { @@ -14337,23 +14582,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; + } + } } } } @@ -14437,7 +14684,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 || @@ -14474,7 +14721,7 @@ var ts; } result = undefined; } - if (ts.hasProperty(moduleExports, name) && + if (moduleExports[name] && moduleExports[name].flags === 8388608 && ts.getDeclarationOfKind(moduleExports[name], 238)) { break; @@ -14503,7 +14750,7 @@ var ts; case 221: case 192: case 222: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064)) { if (lastLocation && lastLocation.flags & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; @@ -14521,7 +14768,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; } @@ -14572,8 +14819,9 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -14601,7 +14849,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); @@ -14630,33 +14878,30 @@ 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 false; + 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 checkResolvedBlockScopedVariable(result, errorLocation) { 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)); } } @@ -14713,7 +14958,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); @@ -14729,9 +14974,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); } } } @@ -14747,25 +14992,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) { + var name_12 = specifier.propertyName || specifier.name; + if (name_12.text) { if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { 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_12.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_12.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_11.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_12.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_12.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_12, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_12)); } return symbol; } @@ -14780,10 +15028,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) { @@ -14804,7 +15052,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."); @@ -14812,6 +15060,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; @@ -14841,6 +15090,7 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); if (node.kind === 235) { checkExpressionCached(node.expression); } @@ -14857,11 +15107,11 @@ 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) { @@ -14873,7 +15123,7 @@ var ts; } var symbol; if (name.kind === 69) { - var message = meaning === 1536 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; @@ -14882,7 +15132,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); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -14940,7 +15190,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(moduleReferenceLiteral, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + } } return undefined; } @@ -14970,7 +15227,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] = { @@ -14978,7 +15235,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]; } @@ -14996,11 +15253,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); @@ -15009,7 +15266,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++) { @@ -15060,8 +15317,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) { @@ -15069,6 +15326,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; @@ -15083,14 +15346,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); } } } @@ -15108,7 +15369,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; @@ -15133,7 +15394,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) { @@ -15150,10 +15411,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)) { @@ -15180,10 +15441,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; } @@ -15226,7 +15487,7 @@ var ts; 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; @@ -15297,10 +15558,10 @@ 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); @@ -15351,6 +15612,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"; @@ -15473,35 +15759,45 @@ var ts; 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) { + 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) { + 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 & 32) { writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } + else if (type.flags & 64) { + writer.writeStringLiteral(type.text); + } else { writePunctuation(writer, 15); writeSpace(writer); @@ -15524,7 +15820,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); @@ -15546,6 +15842,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; @@ -15567,16 +15868,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); } @@ -15593,7 +15894,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); @@ -15995,13 +16296,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) { @@ -16018,7 +16319,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); } @@ -16059,7 +16360,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) { @@ -16101,7 +16402,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); @@ -16138,19 +16439,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_12 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_12)) { + var name_13 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_13)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_12); + var text = getTextOfPropertyName(name_13); 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_13, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_13)); return unknownType; } } @@ -16163,7 +16464,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); @@ -16175,7 +16476,7 @@ 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; @@ -16208,7 +16509,7 @@ 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) { @@ -16243,9 +16544,14 @@ 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); } @@ -16257,26 +16563,24 @@ var ts; 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 checkExpressionCached(element.initializer); } 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; @@ -16287,7 +16591,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; }); @@ -16296,27 +16600,27 @@ 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) { 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 e.kind === 193 ? 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); @@ -16361,14 +16665,21 @@ var ts; if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = undefined; + var type = void 0; if (declaration.kind === 187 || declaration.kind === 172 && declaration.parent.kind === 187) { - type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ? + if (declaration.flags & 134217728) { + 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); })); + checkExpressionCached(decl.parent.right); }); + type = getUnionType(declaredTypes, true); } - if (type === undefined) { + else { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { @@ -16460,9 +16771,9 @@ var ts; 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; @@ -16513,7 +16824,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); @@ -16573,7 +16884,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); @@ -16600,7 +16911,7 @@ var ts; return unknownType; } var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & 80896) { + if (baseConstructorType.flags & 2588672) { resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { @@ -16616,25 +16927,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); @@ -16655,7 +16969,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; } @@ -16688,7 +17002,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]; @@ -16720,8 +17034,8 @@ var ts; 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; } @@ -16735,20 +17049,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; } @@ -16761,8 +17075,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); @@ -16773,12 +17088,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; } } @@ -16790,19 +17105,80 @@ 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 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] = createType(256); + memberType.symbol = memberSymbol; + memberType.baseType = enumType; + memberType.text = "" + 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; @@ -16826,11 +17202,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); @@ -16901,7 +17280,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; @@ -16909,7 +17288,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); @@ -16919,7 +17298,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; } } @@ -16936,19 +17315,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); @@ -16958,7 +17345,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); @@ -16984,7 +17371,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; @@ -16994,11 +17381,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); @@ -17022,22 +17409,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]; @@ -17083,7 +17454,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; @@ -17108,7 +17479,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); @@ -17168,7 +17539,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)); } @@ -17182,41 +17553,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; } } } @@ -17227,7 +17593,7 @@ var ts; var prop = _c[_b]; getPropertyOfUnionOrIntersectionType(type, prop.name); } - if (type.flags & 16384) { + if (type.flags & 524288) { break; } } @@ -17235,12 +17601,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); @@ -17248,19 +17614,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; @@ -17268,7 +17634,7 @@ 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]; @@ -17287,7 +17653,7 @@ var ts; isReadonly = true; } } - else if (containingType.flags & 16384) { + else if (containingType.flags & 524288) { return undefined; } } @@ -17300,11 +17666,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 | @@ -17312,47 +17687,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; } @@ -17362,7 +17736,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; } @@ -17387,7 +17761,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes); + return getUnionType(propTypes, true); } } return undefined; @@ -17470,7 +17844,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; @@ -17490,7 +17864,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) { @@ -17516,6 +17890,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; @@ -17526,7 +17903,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; } @@ -17611,7 +17988,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); @@ -17635,7 +18012,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]; } } @@ -17655,7 +18032,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; @@ -17699,7 +18076,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; } @@ -17731,24 +18108,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; @@ -17758,20 +18138,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; @@ -17821,8 +18210,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; @@ -17831,7 +18221,7 @@ var ts; if (!typeReferenceName) { return unknownSymbol; } - return resolveEntityName(typeReferenceName, 793056) || unknownSymbol; + return resolveEntityName(typeReferenceName, 793064) || unknownSymbol; } function getTypeReferenceType(node, symbol) { if (symbol === unknownSymbol) { @@ -17857,14 +18247,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) : @@ -17899,7 +18289,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; } @@ -17913,7 +18303,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); @@ -17923,8 +18313,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) { @@ -17952,16 +18342,39 @@ 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) { @@ -17969,30 +18382,68 @@ var ts; } 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) { + if (type.flags & 524288) { + addTypesToUnion(typeSet, type.types); + } + else if (type.flags & 1) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && type.flags & 6144) { + if (type.flags & 2048) typeSet.containsUndefined = true; - if (type.flags & 64) + if (type.flags & 4096) typeSet.containsNull = true; - if (!(type.flags & 2097152)) + if (!(type.flags & 33554432)) typeSet.containsNonWideningType = true; } - else if (type !== neverType && !ts.contains(typeSet, type)) { - typeSet.push(type); + else if (!(type.flags & 8192)) { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(type.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])) { @@ -18010,7 +18461,7 @@ var ts; } } } - function getUnionType(types, noSubtypeReduction) { + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -18018,17 +18469,11 @@ 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); } if (typeSet.length === 0) { @@ -18036,78 +18481,103 @@ var ts; 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, getTypeFromTypeNode), 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, getTypeFromTypeNode), 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 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 = checkExpression(node.literal); } return links.resolvedType; } @@ -18146,7 +18616,7 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node) { + function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { switch (node.kind) { case 117: case 258: @@ -18168,11 +18638,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); @@ -18189,9 +18667,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: @@ -18205,7 +18683,7 @@ var ts; case 281: case 269: case 265: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node, aliasSymbol, aliasTypeArguments); case 69: case 139: var symbol = getSymbolAtLocation(node); @@ -18251,6 +18729,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) { @@ -18283,7 +18762,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; @@ -18318,7 +18797,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; @@ -18349,9 +18828,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; } @@ -18403,26 +18884,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; @@ -18465,10 +18943,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; @@ -18479,22 +18957,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); @@ -18607,8 +19088,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; @@ -18634,6 +19115,73 @@ var ts; sourceNonRestParamCount; } } + function isEnumTypeRelatedTo(source, target, errorReporter) { + if (source === target) { + return true; + } + if (source.symbol.name !== target.symbol.name || !(source.symbol.flags & 256) || !(target.symbol.flags & 256)) { + return 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 false; + } + } + } + return 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 | 64) && target.flags & 16) + return true; + if (source.flags & 64 && target.flags & 256 && source.text === target.text) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + 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; @@ -18672,6 +19220,16 @@ 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 === target) @@ -18679,78 +19237,50 @@ var ts; 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 & 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; @@ -18763,14 +19293,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; @@ -18778,22 +19308,25 @@ var ts; } } if (reportErrors) { + if (source.flags & 2588672 && target.flags & 8190) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } 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; @@ -18803,7 +19336,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 || @@ -18812,7 +19345,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)) { @@ -18830,7 +19363,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)) { @@ -18860,14 +19393,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) { @@ -18891,14 +19420,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) { @@ -18970,7 +19495,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = {}; + maybeStack[depth] = ts.createMap(); maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; @@ -19002,7 +19527,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; @@ -19015,7 +19540,7 @@ var ts; } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608); for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -19081,7 +19606,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); @@ -19194,7 +19719,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) || @@ -19231,27 +19756,6 @@ 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; @@ -19274,7 +19778,7 @@ 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); @@ -19286,12 +19790,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; @@ -19333,8 +19837,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; @@ -19384,31 +19890,23 @@ 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; - } - return flags; - } function getCommonSupertype(types) { if (!strictNullChecks) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } - 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); + return supertype && includeFalsyTypes(supertype, getFalsyFlagsOfTypes(types) & 6144); } function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { var bestSupertype; @@ -19438,44 +19936,72 @@ 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 isUnitUnionType(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 getBaseTypeOfUnitType(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, getBaseTypeOfUnitType)) : + 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_8 = types; _i < types_8.length; _i++) { + var t = types_8[_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 === emptyStringType ? 32 : 0 : + type.flags & 64 ? type === zeroType ? 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; @@ -19497,7 +20023,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); @@ -19508,7 +20034,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(type.flags & 1048576)) { + if (!(type.flags & 16777216)) { return type; } var regularType = type.regularType; @@ -19518,7 +20044,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; } @@ -19532,31 +20058,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)) { @@ -19564,22 +20087,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))); } @@ -19624,7 +20144,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); } @@ -19666,12 +20186,24 @@ var ts; isFixed: false }; } + 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 inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = {}; + var visited = ts.createMap(); inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -19682,11 +20214,21 @@ 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]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var t = _c[_b]; if (typeIdenticalToSomeType(t, source.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); @@ -19697,8 +20239,8 @@ var ts; 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; @@ -19717,7 +20259,7 @@ var ts; } } } - 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; @@ -19725,20 +20267,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(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -19752,18 +20287,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; } @@ -19771,7 +20304,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (ts.hasProperty(visited, key)) { + if (visited[key]) { return; } visited[key] = true; @@ -19840,8 +20373,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_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -19856,7 +20389,7 @@ 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]; @@ -19868,7 +20401,7 @@ var ts; if (!inferredType) { var inferences = getInferenceCandidates(context, index); if (inferences.length) { - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences, true) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -19934,10 +20467,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: @@ -19949,16 +20478,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; } @@ -19971,6 +20501,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 && + isUnitUnionType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -19997,7 +20561,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++) { @@ -20009,70 +20573,79 @@ 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) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (reducedType !== neverType) { + return reducedType; } } return declaredType; } + function getTypeFactsOfTypes(types) { + var result = 0; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_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 === emptyStringType ? 3030785 : 1982209 : + type === emptyStringType ? 3145473 : 4194049; + } + if (flags & (4 | 16)) { return strictNullChecks ? 4079234 : 4193922; } + if (flags & (64 | 256)) { + var isZero = type === zeroType || type.flags & 256 && 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) { @@ -20166,51 +20739,86 @@ 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 = 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) { return declaredType; @@ -20250,7 +20858,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; } @@ -20269,16 +20877,9 @@ 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)) : + return declaredType.flags & 524288 ? + getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : declaredType; } if (containsMatchingReference(reference, node)) { @@ -20287,37 +20888,55 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var type = getTypeAtFlowNode(flow.antecedent); + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); if (type !== neverType) { var assumeTrue = (flow.flags & 32) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType) { + if (type === neverType && isIncomplete(flowType)) { type = narrowType(declaredType, flow.expression, assumeTrue); } } - 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); } @@ -20326,32 +20945,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) { @@ -20361,26 +21014,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: @@ -20390,23 +21046,34 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + function narrowTypeByEquality(type, operator, value, assumeTrue) { 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 !== neverType ? narrowedType : type; + } + return isUnitType(valueType) ? filterType(type, function (t) { return t !== valueType; }) : 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; @@ -20416,76 +21083,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 === neverType ? 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, t)); }); + return caseType === neverType ? 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; @@ -20498,12 +21129,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) { @@ -20517,23 +21151,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 !== neverType) { + 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, targetType) ? 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); @@ -20541,6 +21174,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) { @@ -20611,20 +21247,48 @@ 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); @@ -20661,16 +21325,22 @@ var ts; 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); + 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 || + flowContainer !== declarationContainer || 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; } @@ -20833,10 +21503,6 @@ var ts; return getInferredClassType(classSymbol); } } - var type = getContextuallyTypedThisType(container); - if (type) { - return type; - } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -20845,7 +21511,7 @@ 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); + return getFlowTypeOfReference(node, type, true, undefined); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -20978,11 +21644,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; @@ -21039,15 +21705,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_14 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_13)) { - var text = getTextOfPropertyName(name_13); + !ts.isBindingPattern(name_14)) { + var text = getTextOfPropertyName(name_14); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -21122,6 +21788,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); } @@ -21141,14 +21810,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_11 = types; _i < types_11.length; _i++) { + var current = types_11[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -21166,7 +21835,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; }); } @@ -21174,7 +21843,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)); @@ -21280,6 +21949,30 @@ var ts; } return undefined; } + function isLiteralTypeLocation(node) { + var parent = node.parent; + switch (parent.kind) { + case 187: + switch (parent.operatorToken.kind) { + case 32: + case 33: + case 30: + case 31: + return true; + } + break; + case 188: + return (node === parent.whenTrue || + node === parent.whenFalse) && + isLiteralTypeLocation(parent); + case 178: + return isLiteralTypeLocation(parent); + case 249: + case 166: + return true; + } + return false; + } function getNonGenericSignature(type) { var signatures = getSignaturesOfStructuredType(type, 0); if (signatures.length === 1) { @@ -21308,13 +22001,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_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -21370,7 +22063,7 @@ var ts; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { - var type = createNewTupleType(elementTypes); + var type = cloneTypeReference(createTupleType(elementTypes)); type.pattern = node; return type; } @@ -21382,7 +22075,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) { @@ -21397,13 +22090,15 @@ 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); @@ -21415,7 +22110,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 { @@ -21431,13 +22126,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 && @@ -21475,7 +22170,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; @@ -21513,7 +22208,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); } @@ -21525,8 +22220,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; } @@ -21580,9 +22275,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) { @@ -21655,7 +22350,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; } @@ -21667,11 +22362,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) { @@ -21694,16 +22389,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; @@ -21756,7 +22451,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; } @@ -21839,7 +22534,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) { @@ -21857,7 +22552,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)); } } @@ -21918,10 +22613,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; } @@ -21930,9 +22625,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); @@ -21953,13 +22648,13 @@ var ts; 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)); + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 268435456 ? apparentType : type)); } return unknownType; } @@ -21978,12 +22673,15 @@ var ts; checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); + if (prop.flags & 8 && isLiteralContextForType(node, propType)) { + propType = getDeclaredTypeOfSymbol(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 isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 @@ -22061,21 +22759,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_15 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_15 !== undefined) { + var prop = getPropertyOfType(objectType, name_15); 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_15, 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; @@ -22120,7 +22819,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)); } @@ -22184,7 +22883,7 @@ var ts; lastParent = parent_9; } lastSymbol = symbol; - if (signature.hasStringLiterals) { + if (signature.hasLiteralTypes) { specializedIndex++; spliceIndex = specializedIndex; cutoffIndex++; @@ -22258,7 +22957,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) { @@ -22358,9 +23057,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)) { @@ -22464,10 +23161,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 { @@ -22708,8 +23405,8 @@ var ts; 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))) { + (isTypeAny(apparentType) && funcType.flags & 16384) || + (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 524288) && isTypeAssignableTo(funcType, globalFunctionType))) { if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } @@ -22782,6 +23479,18 @@ var ts; var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + if (baseTypes.length) { + var baseType = baseTypes[0]; + if (flags & 16 && + baseType.symbol === declaration.parent.symbol) { + return true; + } + } + } if (flags & 8) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } @@ -22799,7 +23508,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384) && isTypeAssignableTo(tagType, globalFunctionType))) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 524288) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -22830,7 +23539,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 524288) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); @@ -22930,7 +23639,7 @@ var ts; if (strictNullChecks) { var declaration = symbol.valueDeclaration; if (declaration && declaration.initializer) { - return addTypeKind(type, 32); + return includeFalsyTypes(type, 2048); } } return type; @@ -22942,6 +23651,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); @@ -23039,7 +23754,7 @@ var ts; return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } - type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); + type = contextualSignature ? getUnionType(types, true) : getCommonSupertype(types); if (!type) { if (funcIsGenerator) { error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); @@ -23047,7 +23762,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types, true)) : getUnionType(types, true); } } if (funcIsGenerator) { @@ -23077,24 +23792,18 @@ 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 (!isUnitUnionType(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)) { @@ -23144,7 +23853,7 @@ 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)) { @@ -23246,7 +23955,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340)) { error(operand, diagnostic); return false; } @@ -23340,16 +24049,22 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (node.operator === 36 && node.operand.kind === 8 && isLiteralContextForType(node, numberType)) { + return 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); @@ -23372,10 +24087,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_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -23387,20 +24102,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_14 = types; _i < types_14.length; _i++) { + var t = types_14[_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_15 = types; _a < types_15.length; _a++) { + var t = types_15[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -23409,13 +24124,13 @@ 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 (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))) { @@ -23424,10 +24139,10 @@ var ts; return booleanType; } function checkInExpression(left, right, leftType, rightType) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 | 132 | 16777216)) { + 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; @@ -23442,14 +24157,14 @@ var ts; } 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_16 = property.name; + if (name_16.kind === 140) { + checkComputedPropertyName(name_16); } - if (isComputedNonLiteralName(name_15)) { + if (isComputedNonLiteralName(name_16)) { return undefined; } - var text = getTextOfPropertyName(name_15); + var text = getTextOfPropertyName(name_16); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -23464,7 +24179,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_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_16)); } } else { @@ -23494,8 +24209,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); @@ -23525,7 +24241,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); @@ -23555,7 +24271,14 @@ var ts; return sourceType; } 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); @@ -23590,15 +24313,15 @@ var ts; case 68: case 46: case 66: - if (leftType.flags & 96) + 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)); } @@ -23612,18 +24335,18 @@ var ts; return numberType; case 35: case 57: - if (leftType.flags & 96) + 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)) { @@ -23655,6 +24378,12 @@ var ts; case 31: case 32: case 33: + var leftIsUnit = isUnitUnionType(leftType); + var rightIsUnit = isUnitUnionType(rightType); + if (!leftIsUnit || !rightIsUnit) { + leftType = leftIsUnit ? getBaseTypeOfUnitType(leftType) : leftType; + rightType = rightIsUnit ? getBaseTypeOfUnitType(rightType) : rightType; + } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -23664,9 +24393,13 @@ 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 : getBaseTypeOfUnitType(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); @@ -23674,8 +24407,8 @@ var ts; 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)); @@ -23760,14 +24493,63 @@ 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 typeContainsLiteralFromEnum(type, enumType) { + if (type.flags & 524288) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 256 && t.baseType === enumType) { + return true; + } + } + } + if (type.flags & 256) { + return type.baseType === enumType; + } + return false; + } + function isLiteralContextForType(node, type) { + if (isLiteralTypeLocation(node)) { + return true; + } + var contextualType = getContextualType(node); + if (contextualType) { + if (contextualType.flags & 16384) { + var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (type === apparentType) { + return true; + } + contextualType = apparentType; + } + if (type.flags & 2) { + return maybeTypeOfKind(contextualType, 32); + } + if (type.flags & 4) { + return maybeTypeOfKind(contextualType, (64 | 256)); + } + if (type.flags & 8) { + return maybeTypeOfKind(contextualType, 128) && !isTypeAssignableTo(booleanType, contextualType); + } + if (type.flags & 16) { + return typeContainsLiteralFromEnum(contextualType, type); + } + } + return false; + } + function checkLiteralExpression(node) { + if (node.kind === 8) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9: + return isLiteralContextForType(node, stringType) ? getLiteralTypeForText(32, node.text) : stringType; + case 8: + return isLiteralContextForType(node, numberType) ? getLiteralTypeForText(64, node.text) : numberType; + case 99: + case 84: + return isLiteralContextForType(node, booleanType) ? node.kind === 99 ? trueType : falseType : booleanType; } - return stringType; } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { @@ -23840,10 +24622,6 @@ var ts; } return type; } - function checkNumericLiteral(node) { - checkGrammarNumericLiteral(node); - return numberType; - } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69: @@ -23854,15 +24632,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: @@ -24007,9 +24783,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_17 = _a[_i].name; + if (ts.isBindingPattern(name_17) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_17, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -24037,15 +24813,15 @@ var ts; } 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 name_18 = _a[_i].name; + if (name_18.kind === 69 && + name_18.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_18.kind === 168 || + name_18.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_18, predicateVariableNode, predicateVariableName)) { return true; } } @@ -24099,16 +24875,15 @@ var ts; } } 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); } } } @@ -24119,21 +24894,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)); } @@ -24147,7 +24922,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) { @@ -24161,7 +24936,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); } @@ -24303,12 +25078,7 @@ var ts; 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 (!(node.flags & 65536)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -24330,7 +25100,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) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } } if (node.parent.kind !== 171) { checkSourceElement(node.body); @@ -24383,6 +25156,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) { @@ -24652,10 +25428,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; } @@ -24678,7 +25454,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]; @@ -24704,7 +25480,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; @@ -24715,13 +25491,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); @@ -24826,7 +25602,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); @@ -24982,22 +25758,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) && - !parameterIsThisKeyword(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) { @@ -25025,7 +25799,7 @@ var ts; 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); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -25053,14 +25827,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); } } } @@ -25194,8 +25966,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_19 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_19, name_19); } } } @@ -25265,8 +26037,8 @@ var ts; } 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)); + var name_20 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_20)); if (parent_11.initializer && property && getParentOfSymbol(property)) { checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); } @@ -25442,7 +26214,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 { @@ -25450,7 +26222,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); @@ -25503,7 +26275,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 { @@ -25518,7 +26290,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; @@ -25529,7 +26301,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 { @@ -25544,7 +26316,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; } @@ -25564,7 +26336,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) || @@ -25573,10 +26345,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; @@ -25601,10 +26373,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; } @@ -25616,7 +26388,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)) { @@ -25747,7 +26519,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); @@ -25772,7 +26544,7 @@ 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]; @@ -25787,7 +26559,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]; } @@ -25809,7 +26581,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]; } @@ -25917,6 +26689,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; })) { @@ -25930,15 +26707,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 { @@ -26062,7 +26839,7 @@ 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++) { @@ -26070,11 +26847,11 @@ var ts; 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)) { + 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; @@ -26112,7 +26889,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); @@ -26435,9 +27212,6 @@ var ts; } } } - if (compilerOptions.noImplicitAny && !node.body) { - reportImplicitAnyError(node, anyType); - } if (node.body) { checkSourceElement(node.body); if (!ts.isGlobalScopeAugmentation(node)) { @@ -26463,9 +27237,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_21 = node.name; + if (ts.isBindingPattern(name_21)) { + for (var _b = 0, _c = name_21.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -26491,19 +27265,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); @@ -26531,8 +27306,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 : @@ -26586,11 +27361,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); } } @@ -26634,7 +27409,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); } @@ -26696,7 +27471,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); @@ -26866,9 +27641,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); @@ -26939,7 +27715,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = {}; + var symbols = ts.createMap(); var memberFlags = 0; if (isInsideWithStatementBody(location)) { return []; @@ -26970,7 +27746,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: @@ -26991,7 +27767,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; } } @@ -27079,15 +27855,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; @@ -27095,13 +27869,13 @@ 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); @@ -27132,7 +27906,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) { @@ -27224,7 +27998,7 @@ 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)) { @@ -27305,7 +28079,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; } }); @@ -27315,9 +28089,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_21 = symbol.name; + var name_22 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_21); + var symbol = getPropertyOfType(t, name_22); if (symbol) { symbols_3.push(symbol); } @@ -27350,7 +28124,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) { @@ -27494,7 +28268,7 @@ 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); @@ -27502,7 +28276,7 @@ var ts; if (constructorType && isConstructorType(constructorType)) { return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } - var typeSymbol = resolveEntityName(typeName, 793056, true); + var typeSymbol = resolveEntityName(typeName, 793064, true); if (!typeSymbol) { return ts.TypeReferenceSerializationKind.ObjectType; } @@ -27513,22 +28287,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 16)) { + else if (isTypeOfKind(type, 1024)) { return ts.TypeReferenceSerializationKind.VoidType; } - 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)) { @@ -27563,7 +28337,7 @@ 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 || @@ -27580,9 +28354,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; @@ -27626,7 +28397,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; } @@ -27732,7 +28503,7 @@ 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"); }); @@ -27752,7 +28523,7 @@ 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; } @@ -27766,7 +28537,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 = []; @@ -27794,49 +28565,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; @@ -28029,6 +28760,56 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } + 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) { if (languageVersion < 2) { return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); @@ -28261,16 +29042,16 @@ 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; + var name_23 = prop.name; if (prop.kind === 193 || - name_22.kind === 140) { - checkGrammarComputedPropertyName(name_22); + name_23.kind === 140) { + checkGrammarComputedPropertyName(name_23); } 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) }; @@ -28283,8 +29064,8 @@ var ts; 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_23.kind === 8) { + checkGrammarNumericLiteral(name_23); } currentKind = Property; } @@ -28300,28 +29081,28 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_22); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_23); if (effectiveName === undefined) { return "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_23, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_23)); } 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 { value: grammarErrorOnNode(name_23, 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 { value: grammarErrorOnNode(name_23, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } }; @@ -28332,19 +29113,19 @@ var ts; } } 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_24 = jsxAttr.name; + if (!seen[name_24.text]) { + seen[name_24.text] = true; } else { - return grammarErrorOnNode(name_23, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_24, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -28668,6 +29449,7 @@ var ts; node.kind === 229 || node.kind === 236 || node.kind === 235 || + node.kind === 228 || (node.flags & 2) || (node.flags & (1 | 512))) { return false; @@ -28719,7 +29501,6 @@ var ts; return true; } } - var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -28753,6 +29534,7 @@ var ts; ts.getNullSourceMapWriter = getNullSourceMapWriter; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var sourceMapDir; var stopOverridingSpan = false; @@ -28881,6 +29663,9 @@ var ts; if (pos === -1) { return; } + if (extendedDiagnostics) { + ts.performance.mark("beforeSourcemap"); + } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); sourceLinePos.line++; sourceLinePos.character++; @@ -28908,6 +29693,10 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); + if (extendedDiagnostics) { + ts.performance.mark("afterSourcemap"); + ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); + } } function getStartPos(range) { var rangeHasDecorators = !!range.decorators; @@ -29085,9 +29874,7 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { - referencesOutput += "/// " + newLine; - } + referencesOutput += "/// " + newLine; } } return { @@ -29176,11 +29963,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; } } @@ -29332,7 +30119,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) { @@ -29401,15 +30188,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_25 = baseName + "_" + count; + if (!(name_25 in currentIdentifiers)) { + return name_25; } } } @@ -29824,7 +30611,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) { @@ -29922,7 +30709,8 @@ 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) { @@ -30458,7 +31246,7 @@ var ts; return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - var entities = { + var entities = ts.createMap({ "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -30712,7 +31500,7 @@ var ts; "clubs": 0x2663, "hearts": 0x2665, "diams": 0x2666 - }; + }); function emitFiles(resolver, host, targetSourceFile) { 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};"; @@ -30738,7 +31526,7 @@ var ts; }; 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 in node.locals) { if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { return false; } @@ -30749,13 +31537,13 @@ var ts; function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = {}; + state.labeledNonLocalBreaks = ts.createMap(); } state.labeledNonLocalBreaks[labelText] = labelMarker; } else { if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = {}; + state.labeledNonLocalContinues = ts.createMap(); } state.labeledNonLocalContinues[labelText] = labelMarker; } @@ -30813,26 +31601,26 @@ var ts; var isOwnFileEmit; var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; - var moduleEmitDelegates = (_a = {}, + var moduleEmitDelegates = ts.createMap((_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 = {}, + )); + var bundleEmitDelegates = ts.createMap((_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 = {}; + generatedNameSet = ts.createMap(); nodeToGeneratedName = []; decoratedClassAliases = []; isOwnFileEmit = !isBundledEmit; @@ -30891,24 +31679,24 @@ var ts; } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentFileIdentifiers, name) && - !ts.hasProperty(generatedNameSet, name); + !(name in currentFileIdentifiers) && + !(name in generatedNameSet); } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_25 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_25)) { + var name_26 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_26)) { tempFlags |= flags; - return name_25; + return name_26; } } 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; + var name_27 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_27)) { + return name_27; } } } @@ -31606,8 +32394,8 @@ var ts; } 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); + var name_28 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_28); if (languageVersion === 0 && identifier === "default") { write('["default"]'); } @@ -31674,8 +32462,8 @@ var ts; function emitIdentifier(node) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_28 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_28); + var name_29 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_29); return; } } @@ -31789,6 +32577,10 @@ var ts; else if (node.parent.kind === 188 && node.parent.condition === node) { return true; } + else if (node.parent.kind === 185 || node.parent.kind === 181 || + node.parent.kind === 182 || node.parent.kind === 183) { + return true; + } return false; } function needsParenthesisForPropertyAccessOrInvocation(node) { @@ -32127,9 +32919,9 @@ var ts; 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); + var name_30 = ts.createSynthesizedNode(9); + name_30.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_30); return; } emit(node.expression); @@ -32375,6 +33167,7 @@ var ts; operand.kind !== 181 && operand.kind !== 186 && operand.kind !== 175 && + !(operand.kind === 187 && node.expression.kind === 195) && !(operand.kind === 174 && node.parent.kind === 175) && !(operand.kind === 179 && node.parent.kind === 174) && !(operand.kind === 8 && node.parent.kind === 172)) { @@ -32416,7 +33209,7 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); + return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 @@ -32877,12 +33670,12 @@ var ts; for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { var id = _d[_c]; if (!seen) { - seen = {}; + seen = ts.createMap(); } else { write(", "); } - if (!ts.hasProperty(seen, id.text)) { + if (!(id.text in seen)) { emit(id); seen[id.text] = id.text; } @@ -33335,7 +34128,7 @@ var ts; } if (convertedLoopState) { if (!convertedLoopState.labels) { - convertedLoopState.labels = {}; + convertedLoopState.labels = ts.createMap(); } convertedLoopState.labels[node.label.text] = node.label.text; } @@ -33433,7 +34226,7 @@ var ts; if (modulekind === ts.ModuleKind.System) { return; } - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + if (!exportEquals && exportSpecifiers && name.text in exportSpecifiers) { for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { var specifier = _b[_a]; writeLine(); @@ -33802,12 +34595,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_30 = createTempVariable(0); + var name_31 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_30); - emit(name_30); + tempParameters.push(name_31); + emit(name_31); } else { emit(node.name); @@ -33866,11 +34659,12 @@ var ts; } function emitRestParameter(node) { if (languageVersion < 2 && ts.hasDeclaredRestParameter(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; + var restParam = node.parameters[node.parameters.length - 1]; if (ts.isBindingPattern(restParam.name)) { return; } + var skipThisCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; + var restIndex = node.parameters.length - 1 - skipThisCount; var tempName = createTempVariable(268435456).text; writeLine(); emitLeadingComments(restParam); @@ -33983,7 +34777,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; + var skipCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 ? 1 : 0; var omitCount = languageVersion < 2 && ts.hasDeclaredRestParameter(node) ? 1 : 0; emitList(parameters, skipCount, parameters.length - omitCount - skipCount, false, false); } @@ -34400,12 +35194,7 @@ var ts; emitSignatureParameters(ctor); } else { - if (baseTypeElement) { - write("(...args)"); - } - else { - write("()"); - } + write("()"); } } var startIndex = 0; @@ -34437,7 +35226,7 @@ var ts; write("_super.apply(this, arguments);"); } else { - write("super(...args);"); + write("super(...arguments);"); } emitEnd(baseTypeElement); } @@ -34515,7 +35304,7 @@ var ts; var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192; var generatedName; if (isClassExpressionWithStaticProperties) { - generatedName = getGeneratedNameForNode(node.name); + generatedName = node.name ? getGeneratedNameForNode(node.name) : makeUniqueName("classExpression"); var synthesizedNode = ts.createSynthesizedNode(69); synthesizedNode.text = generatedName; recordTempDeclaration(synthesizedNode); @@ -34965,10 +35754,11 @@ var ts; } if (valueDeclaration) { var parameters = valueDeclaration.parameters; + var skipThisCount = parameters.length && parameters[0].name.originalKeywordKind === 97 ? 1 : 0; var parameterCount = parameters.length; - if (parameterCount > 0) { - for (var i = 0; i < parameterCount; i++) { - if (i > 0) { + if (parameterCount > skipThisCount) { + for (var i = skipThisCount; i < parameterCount; i++) { + if (i > skipThisCount) { write(", "); } if (parameters[i].dotDotDotToken) { @@ -35223,7 +36013,7 @@ var ts; } } function tryRenameExternalModule(moduleName) { - if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { + if (renamedDependencies && moduleName.text in renamedDependencies) { return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; @@ -35523,7 +36313,7 @@ var ts; } function collectExternalModuleInfo(sourceFile) { externalImports = []; - exportSpecifiers = {}; + exportSpecifiers = ts.createMap(); exportEquals = undefined; hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { @@ -35555,8 +36345,8 @@ var ts; 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); + var name_32 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_32] || (exportSpecifiers[name_32] = [])).push(specifier); } } break; @@ -35594,9 +36384,9 @@ var ts; } function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { if (emitRelativePathAsModuleName) { - var name_32 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_32) { - return "\"" + name_32 + "\""; + var name_33 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_33) { + return "\"" + name_33 + "\""; } } var moduleName = ts.getExternalModuleName(importNode); @@ -35635,7 +36425,7 @@ var ts; if (!hasExportStarsToExportValues) { return undefined; } - if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { + if (!exportedDeclarations && !ts.someProperties(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; @@ -35739,15 +36529,15 @@ var ts; if (hoistedVars) { writeLine(); write("var "); - var seen = {}; + var seen = ts.createMap(); for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_33 = local.kind === 69 + var name_34 = local.kind === 69 ? local : local.name; - if (name_33) { - var text = ts.unescapeIdentifier(name_33.text); - if (ts.hasProperty(seen, text)) { + if (name_34) { + var text = ts.unescapeIdentifier(name_34.text); + if (text in seen) { continue; } else { @@ -35825,15 +36615,15 @@ var ts; } if (node.kind === 218 || node.kind === 169) { if (shouldHoistVariable(node, false)) { - var name_34 = node.name; - if (name_34.kind === 69) { + var name_35 = node.name; + if (name_35.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_34); + hoistedVars.push(name_35); } else { - ts.forEachChild(name_34, visit); + ts.forEachChild(name_35, visit); } } return; @@ -35990,7 +36780,7 @@ var ts; write("System.register("); writeModuleName(node, emitRelativePathAsModuleName); write("["); - var groupIndices = {}; + var groupIndices = ts.createMap(); var dependencyGroups = []; for (var i = 0; i < externalImports.length; i++) { var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); @@ -35998,7 +36788,7 @@ var ts; continue; } var key = text.substr(1, text.length - 2); - if (ts.hasProperty(groupIndices, key)) { + if (key in groupIndices) { var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); continue; @@ -36739,11 +37529,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.programTime = 0; - ts.emitTime = 0; - ts.ioReadTime = 0; - ts.ioWriteTime = 0; - ts.version = "2.1.0"; + ts.version = "2.0.2"; var emptyArray = []; var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { @@ -36826,43 +37612,26 @@ var ts; 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") { @@ -36874,6 +37643,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) { @@ -37096,7 +37874,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); @@ -37220,9 +37998,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); @@ -37230,39 +38008,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) { @@ -37270,7 +38046,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; } @@ -37289,6 +38067,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); @@ -37361,14 +38142,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(); } @@ -37376,9 +38151,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) { @@ -37391,7 +38167,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)) { @@ -37410,11 +38186,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 && @@ -37432,7 +38208,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); @@ -37440,7 +38216,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) { @@ -37481,8 +38258,8 @@ var ts; 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]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; if (diagnostic.file) { var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; var fileName = diagnostic.file.fileName; @@ -37523,25 +38300,17 @@ var ts; return []; } var resolutions = []; - var cache = {}; + var cache = ts.createMap(); 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 name_36 = names_1[_i]; + var result = name_36 in cache + ? cache[name_36] + : cache[name_36] = loader(name_36, 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; } @@ -37552,7 +38321,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)); + } + } } } } @@ -37567,13 +38344,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 maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; var currentNodeModulesDepth = 0; - var modulesWithElidedImports = {}; - var sourceFilesFoundSearchingNodeModules = {}; - var start = new Date().getTime(); + var modulesWithElidedImports = ts.createMap(); + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -37600,10 +38377,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]); @@ -37647,7 +38423,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") { @@ -37666,10 +38443,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; @@ -37692,7 +38469,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); @@ -37782,7 +38559,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 }; @@ -37819,9 +38596,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) { @@ -37960,16 +38738,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) { @@ -38013,8 +38791,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; @@ -38201,7 +38979,7 @@ 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(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) { + if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { sourceFilesFoundSearchingNodeModules[file_1.path] = false; if (!options.noResolve) { processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); @@ -38210,7 +38988,7 @@ var ts; modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } - else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { + else if (file_1 && modulesWithElidedImports[file_1.path]) { if (currentNodeModulesDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); @@ -38262,13 +39040,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) { @@ -38285,7 +39064,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; } @@ -38319,7 +39098,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++) { @@ -38411,6 +39190,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; @@ -38456,7 +39238,7 @@ 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)); @@ -38467,17 +39249,17 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.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 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.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 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); } } if (options.outDir || @@ -39175,10 +39957,10 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_36 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_36); + for (var name_37 in nameToDeclarations) { + var declarations = nameToDeclarations[name_37]; if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_37); if (!matches) { continue; } @@ -39189,14 +39971,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_36); + matches = patternMatcher.getMatches(containers, name_37); 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_37, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -39442,9 +40224,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_38 = decl.name; + if (ts.isBindingPattern(name_38)) { + addChildrenRecursively(name_38); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { addChildrenRecursively(decl.initializer); @@ -39505,14 +40287,14 @@ var ts; } } 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; @@ -39740,7 +40522,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, @@ -39751,7 +40533,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, @@ -39771,46 +40553,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); @@ -39878,7 +40620,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); @@ -39921,7 +40663,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!ts.hasProperty(stringToWordSpans, word)) { + if (!(word in stringToWordSpans)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -40315,7 +41057,7 @@ 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]; @@ -40759,7 +41501,7 @@ var ts; 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) { + if (c.kind === 286 && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -40911,8 +41653,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && - (previousToken.kind === 9 || previousToken.kind === 166)) { + if (previousToken && previousToken.kind === 9) { var start = previousToken.getStart(); var end = previousToken.getEnd(); if (start < position && position < end) { @@ -41061,7 +41802,6 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 - || kind === 166 || kind === 10 || ts.isTemplateLiteralKind(kind)) { return true; @@ -41341,12 +42081,31 @@ var ts; if (host && host.getScriptKind) { scriptKind = host.getScriptKind(fileName); } - if (!scriptKind || scriptKind === 0) { + 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_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; + diagnostic.start = diagnostic.start - 1; + } + return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + } + ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -41356,20 +42115,14 @@ var ts; ; var safeList; function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { - var inferredTypings = {}; + 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); }); - if (result.config) { - safeList = result.config; - } - else { - safeList = {}; - } - ; + safeList = ts.createMap(result.config); } var filesToWatch = []; var searchDirs = []; @@ -41392,7 +42145,7 @@ var ts; } getTypingNamesFromSourceFileNames(fileNames); for (var name_39 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + if (name_39 in inferredTypings && !inferredTypings[name_39]) { inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } @@ -41417,7 +42170,7 @@ var ts; } for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { var typing = typingNames_1[_i]; - if (!ts.hasProperty(inferredTypings, typing)) { + if (!(typing in inferredTypings)) { inferredTypings[typing] = undefined; } } @@ -41428,16 +42181,16 @@ var ts; var jsonConfig = result.config; filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { - mergeTypings(ts.getKeys(jsonConfig.dependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } if (jsonConfig.devDependencies) { - mergeTypings(ts.getKeys(jsonConfig.devDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); } if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); } if (jsonConfig.peerDependencies) { - mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); } } } @@ -41449,7 +42202,7 @@ var ts; mergeTypings(cleanedTypingNames); } else { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); + 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) { @@ -41954,7 +42707,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)); @@ -41985,6 +42738,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, @@ -42011,6 +42769,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, @@ -42038,8 +42798,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)); @@ -42065,10 +42825,10 @@ 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)); } @@ -42243,12 +43003,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); }; @@ -43956,7 +44725,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(282, nodes.pos, nodes.end, 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++) { @@ -43979,13 +44748,16 @@ var 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) { @@ -44410,7 +45182,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; }; @@ -44467,7 +45239,7 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = {}; + var result = ts.createMap(); ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { @@ -44478,13 +45250,13 @@ var ts; } } 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_3 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_3 !== undefined) { + return result_3; } if (declaration.name.kind === 140) { var expr = declaration.name.expression; @@ -44661,6 +45433,7 @@ var ts; ScriptElementKind.interfaceElement = "interface"; ScriptElementKind.typeElement = "type"; ScriptElementKind.enumElement = "enum"; + ScriptElementKind.enumMemberElement = "const"; ScriptElementKind.variableElement = "var"; ScriptElementKind.localVariableElement = "local var"; ScriptElementKind.functionElement = "function"; @@ -44854,7 +45627,7 @@ var ts; 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"; }); + return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); var _loop_3 = function(opt) { @@ -44866,7 +45639,7 @@ var ts; options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); } else { - if (!ts.forEachValue(opt.type, function (v) { return v === value; })) { + if (!ts.forEachProperty(opt.type, function (v) { return v === value; })) { diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); } } @@ -44900,7 +45673,9 @@ var ts; if (transpileOptions.moduleName) { sourceFile.moduleName = transpileOptions.moduleName; } - sourceFile.renamedDependencies = transpileOptions.renamedDependencies; + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMap(transpileOptions.renamedDependencies); + } var newLine = ts.getNewLineCharacter(options); var outputText; var sourceMapText; @@ -44990,13 +45765,13 @@ var ts; ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { if (currentDirectory === void 0) { currentDirectory = ""; } - var buckets = {}; + 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 = ts.lookUp(buckets, key); + var bucket = buckets[key]; if (!bucket && createIfMissing) { buckets[key] = bucket = ts.createFileMap(); } @@ -45004,7 +45779,7 @@ var ts; } 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 entries = buckets[name]; var sourceFiles = []; entries.forEachValue(function (key, entry) { sourceFiles.push({ @@ -45534,7 +46309,10 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 225: return ScriptElementKind.moduleElement; + case 256: + return ts.isExternalModule(node) ? ScriptElementKind.moduleElement : ScriptElementKind.scriptElement; + case 225: + return ScriptElementKind.moduleElement; case 221: case 192: return ScriptElementKind.classElement; @@ -45542,11 +46320,10 @@ var ts; 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; + return getKindOfVariableDeclaration(node); + case 169: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 180: case 220: case 179: return ScriptElementKind.functionElement; @@ -45563,7 +46340,7 @@ var ts; case 151: return ScriptElementKind.callSignatureElement; case 148: return ScriptElementKind.constructorImplementationElement; case 141: return ScriptElementKind.typeParameterElement; - case 255: return ScriptElementKind.variableElement; + case 255: return ScriptElementKind.enumMemberElement; case 142: return (node.flags & 92) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; case 229: case 234: @@ -45571,8 +46348,18 @@ var ts; case 238: case 232: return ScriptElementKind.alias; + case 279: + return ScriptElementKind.typeElement; + default: + return ScriptElementKind.unknown; + } + function getKindOfVariableDeclaration(v) { + return ts.isConst(v) + ? ScriptElementKind.constElement + : ts.isLet(v) + ? ScriptElementKind.letElement + : ScriptElementKind.variableElement; } - return ScriptElementKind.unknown; } ts.getNodeKind = getNodeKind; var CancellationTokenObject = (function () { @@ -45637,14 +46424,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, @@ -45656,7 +46445,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) { @@ -45688,7 +46476,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); } } @@ -45706,7 +46494,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); @@ -45774,7 +46562,7 @@ var ts; var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); if (displayName) { var firstCharCode = displayName.charCodeAt(0); - if ((symbol.flags & 1536) && (firstCharCode === 39 || firstCharCode === 34)) { + if ((symbol.flags & 1920) && (firstCharCode === 39 || firstCharCode === 34)) { return undefined; } } @@ -45800,12 +46588,12 @@ var ts; var sourceFile = getValidSourceFile(fileName); var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var isJsDocTagName = false; - var start = new Date().getTime(); + var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); - log("getCompletionData: Get current token: " + (new Date().getTime() - start)); - start = new Date().getTime(); + log("getCompletionData: Get current token: " + (ts.timestamp() - start)); + start = ts.timestamp(); var insideComment = isInsideComment(sourceFile, currentToken, position); - log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); + log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); if (insideComment) { if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64) { isJsDocTagName = true; @@ -45835,14 +46623,14 @@ var ts; return undefined; } } - start = new Date().getTime(); + start = ts.timestamp(); var previousToken = ts.findPrecedingToken(position, sourceFile); - log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); + log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); var contextToken = previousToken; if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_5 = new Date().getTime(); + var start_2 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); } var node = currentToken; var isRightOfDot = false; @@ -45879,7 +46667,7 @@ var ts; } } } - var semanticStart = new Date().getTime(); + var semanticStart = ts.timestamp(); var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -45911,7 +46699,7 @@ var ts; return undefined; } } - log("getCompletionData: Semantic work: " + (new Date().getTime() - semanticStart)); + 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; @@ -45941,7 +46729,7 @@ var ts; symbols.push(symbol); } } - if (isJavaScriptFile && type.flags & 16384) { + if (isJavaScriptFile && type.flags & 524288) { var unionType = type; for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { var elementType = _c[_b]; @@ -45981,7 +46769,7 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - var symbolMeanings = 793056 | 107455 | 1536 | 8388608; + var symbolMeanings = 793064 | 107455 | 1920 | 8388608; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); return true; } @@ -45993,12 +46781,12 @@ var ts; return scope; } function isCompletionListBlocker(contextToken) { - var start = new Date().getTime(); + var start = ts.timestamp(); var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || isSolelyIdentifierDefinitionLocation(contextToken) || isDotOfNumericLiteral(contextToken) || isInJsxText(contextToken); - log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); return result; } function isInJsxText(contextToken) { @@ -46066,12 +46854,11 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 - || contextToken.kind === 166 || contextToken.kind === 10 || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_6 = contextToken.getStart(); + var start_3 = contextToken.getStart(); var end = contextToken.getEnd(); - if (start_6 < position && position < end) { + if (start_3 < position && position < end) { return true; } if (position === end) { @@ -46088,6 +46875,7 @@ var ts; if (objectLikeContainer.kind === 171) { isNewIdentifierLocation = true; typeForObject = typeChecker.getContextualType(objectLikeContainer); + typeForObject = typeForObject && typeForObject.getNonNullableType(); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 167) { @@ -46317,7 +47105,7 @@ var ts; return false; } function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = {}; + 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()) { @@ -46326,16 +47114,16 @@ var ts; var name_41 = element.propertyName || element.name; existingImportsOrExports[name_41.text] = true; } - if (ts.isEmpty(existingImportsOrExports)) { + if (!ts.someProperties(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); }); + 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 = {}; + 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 && @@ -46358,10 +47146,10 @@ var ts; } existingMemberNames[existingName] = true; } - return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames[m.name]; }); } function filterJsxAttributes(symbols, attributes) { - var seenNames = {}; + 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()) { @@ -46371,7 +47159,7 @@ var ts; seenNames[attr.name.text] = true; } } - return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); + return ts.filter(symbols, function (a) { return !seenNames[a.name]; }); } } function getCompletionsAtPosition(fileName, position) { @@ -46414,7 +47202,7 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var target = program.getCompilerOptions().target; @@ -46462,22 +47250,22 @@ var ts; }; } function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { - var start = new Date().getTime(); - var uniqueNames = {}; + 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 (!ts.lookUp(uniqueNames, id)) { + if (!uniqueNames[id]) { entries.push(entry); uniqueNames[id] = id; } } } } - log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniqueNames; } function getStringLiteralCompletionEntries(sourceFile, position) { @@ -46485,18 +47273,32 @@ var ts; if (!node || node.kind !== 9) { return undefined; } - var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo); + 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 { + var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile); + if (argumentInfo) { + return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node); + } return getStringLiteralCompletionEntriesFromContextualType(node); } } - function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element) { + var typeChecker = program.getTypeChecker(); + 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 typeChecker = program.getTypeChecker(); var candidates = []; var entries = []; @@ -46541,11 +47343,11 @@ var ts; if (!type) { return; } - if (type.flags & 16384) { + if (type.flags & 524288) { ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); } else { - if (type.flags & 256) { + if (type.flags & 32) { result.push({ name: type.text, kindModifiers: ScriptElementKindModifier.none, @@ -46744,7 +47546,7 @@ var ts; displayParts.push(ts.keywordPart(92)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 65536) && type.symbol) { + if (!(type.flags & 2097152) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); } addSignatureDisplayParts(signature, allSignatures, 8); @@ -46805,7 +47607,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(56)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512)); } if (symbolFlags & 384) { addNewLineIfDisplayPartsExist(); @@ -46879,7 +47681,14 @@ var ts; } if (symbolFlags & 8388608) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(89)); + 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) { @@ -46950,6 +47759,24 @@ var ts; } 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 = program.getTypeChecker().getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(); + if (documentation.length > 0) { + break; + } + } + } + } } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; function addNewLineIfDisplayPartsExist() { @@ -47146,7 +47973,7 @@ var ts; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { - var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); + var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; if (referenceFile && referenceFile.resolvedFileName) { return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } @@ -47203,14 +48030,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 16384) { - var result_3 = []; + if (type.flags & 524288 && !(type.flags & 16)) { + var result_4 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result_3, getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(result_4, getDefinitionFromSymbol(t.symbol, node)); } }); - return result_3; + return result_4; } if (!type.symbol) { return undefined; @@ -47258,14 +48085,14 @@ var ts; if (!referencedSymbols) { return undefined; } - var fileNameToDocumentHighlights = {}; + var fileNameToDocumentHighlights = ts.createMap(); 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); + var documentHighlights = fileNameToDocumentHighlights[fileName_1]; if (!documentHighlights) { documentHighlights = { fileName: fileName_1, highlightSpans: [] }; fileNameToDocumentHighlights[fileName_1] = documentHighlights; @@ -47834,7 +48661,7 @@ var ts; var sourceFile = sourceFiles_4[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName) !== undefined) { + if (nameTable[internedName] !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -48272,7 +49099,7 @@ var ts; result.push(rootSymbol); } if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, {}); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, ts.createMap()); } }); return result; @@ -48281,7 +49108,7 @@ var ts; if (!symbol) { return; } - if (ts.hasProperty(previousIterationSymbolsCache, symbol.name)) { + if (symbol.name in previousIterationSymbolsCache) { return; } if (symbol.flags & (32 | 64)) { @@ -48340,9 +49167,9 @@ var ts; 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; }); + var result_5 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_5, ts.createMap()); + return ts.forEach(result_5, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -48362,20 +49189,20 @@ var ts; 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); + var result_6 = []; + var symbol_2 = contextualType.getProperty(name); + if (symbol_2) { + result_6.push(symbol_2); } - if (contextualType.flags & 16384) { + if (contextualType.flags & 524288) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -48590,7 +49417,6 @@ var ts; case 172: case 139: case 9: - case 166: case 84: case 99: case 93: @@ -48891,6 +49717,9 @@ var ts; } } function tryClassifyNode(node) { + if (ts.isJSDocTag(node)) { + return true; + } if (ts.nodeIsMissing(node)) { return true; } @@ -48965,7 +49794,7 @@ var ts; else if (tokenKind === 8) { return 4; } - else if (tokenKind === 9 || tokenKind === 166) { + else if (tokenKind === 9) { return token.parent.kind === 246 ? 24 : 6; } else if (tokenKind === 10) { @@ -49077,12 +49906,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) { @@ -49268,7 +50097,7 @@ var ts; function getStringLiteralTypeForNode(node, typeChecker) { var searchNode = node.parent.kind === 166 ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 256) { + if (type && type.flags & 32) { return type; } return undefined; @@ -49410,7 +50239,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = {}; + var nameTable = ts.createMap(); walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -49478,7 +50307,7 @@ var ts; 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 length_4 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -49486,8 +50315,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } - entries.push({ length: length_3, classification: convertClassification(type) }); - lastEnd = start + length_3; + entries.push({ length: length_4, classification: convertClassification(type) }); + lastEnd = start + length_4; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -49623,7 +50452,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9 || token === 166) { + if (token === 9) { var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { var lastCharIndex = tokenText.length - 1; @@ -49753,7 +50582,6 @@ var ts; case 8: return 4; case 9: - case 166: return 6; case 10: return 7; @@ -49923,7 +50751,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 }; @@ -50059,18 +50887,24 @@ var ts; return { responseRequired: false }; }, _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) { @@ -50834,7 +51668,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; @@ -50965,18 +51799,21 @@ 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); + var resolution = newResolutions[name_43]; if (!resolution) { - var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_43); + var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_43]; if (moduleResolutionIsValid(existingResolution)) { resolution = existingResolution; } @@ -51164,7 +52001,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) { @@ -51248,7 +52085,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); @@ -51293,7 +52130,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) { @@ -51327,15 +52164,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 () { @@ -51383,7 +52220,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())) { @@ -51391,14 +52229,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++) { @@ -51415,8 +52265,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"; } @@ -51486,13 +52339,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 } }); } } } @@ -51512,7 +52365,7 @@ 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); } @@ -51720,12 +52573,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)) { @@ -51790,7 +52643,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 { @@ -51804,14 +52657,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; @@ -51819,13 +52673,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); @@ -51889,30 +52743,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) { @@ -51934,45 +52783,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; @@ -51981,22 +52829,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); @@ -52010,7 +52858,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); }); @@ -52049,6 +52897,7 @@ var ts; project.setProjectOptions(projectOptions); project.finishGraph(); } + return errors; } }; ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { @@ -52995,7 +53844,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; }); }; @@ -53006,7 +53855,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); }); }; } } @@ -53093,7 +53942,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; @@ -53143,6 +53992,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; @@ -53150,11 +54002,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; @@ -53481,6 +54333,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; @@ -53604,4 +54463,4 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "1.9"; +var toolsVersion = "2.0"; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 92937fecf99..4855f1511ad 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,8 +318,12 @@ declare namespace ts { JSDocTypedefTag = 279, JSDocPropertyTag = 280, JSDocTypeLiteral = 281, - SyntaxList = 282, - Count = 283, + JSDocLiteralType = 282, + JSDocNullKeyword = 283, + JSDocUndefinedKeyword = 284, + JSDocNeverKeyword = 285, + SyntaxList = 286, + Count = 287, FirstAssignment = 56, LastAssignment = 68, FirstReservedWord = 70, @@ -341,9 +348,9 @@ declare namespace ts { LastBinaryOperator = 68, FirstNode = 139, FirstJSDocNode = 257, - LastJSDocNode = 281, + LastJSDocNode = 282, FirstJSDocTagNode = 273, - LastJSDocTagNode = 281, + LastJSDocTagNode = 285, } enum NodeFlags { None = 0, @@ -607,8 +614,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; @@ -714,11 +722,17 @@ declare namespace ts { interface ObjectLiteralExpression extends PrimaryExpression, Declaration { properties: NodeArray; } + 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; @@ -1031,6 +1045,9 @@ 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; @@ -1109,6 +1126,11 @@ declare namespace ts { clauseEnd: number; antecedent: FlowNode; } + type FlowType = Type | IncompleteType; + interface IncompleteType { + flags: TypeFlags; + type: Type; + } interface AmdDependency { path: string; name: string; @@ -1305,6 +1327,7 @@ declare namespace ts { InElementType = 64, UseFullyQualifiedType = 128, InFirstTypeArgument = 256, + InTypeAlias = 512, } enum SymbolFormatFlags { None = 0, @@ -1363,18 +1386,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, @@ -1382,8 +1405,8 @@ declare namespace ts { MethodExcludes = 99263, GetAccessorExcludes = 41919, SetAccessorExcludes = 74687, - TypeParameterExcludes = 530912, - TypeAliasExcludes = 793056, + TypeParameterExcludes = 530920, + TypeAliasExcludes = 793064, AliasExcludes = 8388608, ModuleMember = 8914931, ExportHasLocal = 944, @@ -1403,49 +1426,63 @@ 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, + 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; } + interface EnumType extends Type { + memberTypes: Map; + } + interface EnumLiteralType extends LiteralType { + baseType: EnumType & UnionType; + } interface ObjectType extends Type { } interface InterfaceType extends ObjectType { @@ -1467,9 +1504,6 @@ declare namespace ts { } interface GenericType extends InterfaceType, TypeReference { } - interface TupleType extends ObjectType { - elementTypes: Type[]; - } interface UnionOrIntersectionType extends Type { types: Type[]; } @@ -1534,7 +1568,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 { @@ -1659,7 +1693,7 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; - wildcardDirectories?: Map; + wildcardDirectories?: MapLike; } enum WatchDirectoryFlags { None = 0, @@ -1667,7 +1701,7 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - wildcardDirectories: Map; + wildcardDirectories: MapLike; } interface ModuleResolutionHost { fileExists(fileName: string): boolean; @@ -1676,6 +1710,7 @@ declare namespace ts { directoryExists?(directoryName: string): boolean; realpath?(path: string): string; getCurrentDirectory?(): string; + getDirectories?(path: string): string[]; } interface ResolvedModule { resolvedFileName: string; @@ -1876,14 +1911,14 @@ declare namespace ts { 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 { @@ -1989,7 +2024,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; } @@ -2437,6 +2472,7 @@ declare namespace ts { const typeElement: string; /** enum E */ const enumElement: string; + const enumMemberElement: string; /** * Inside module and script only * const v = .. @@ -2549,7 +2585,7 @@ declare namespace ts { fileName?: string; reportDiagnostics?: boolean; moduleName?: string; - renamedDependencies?: Map; + renamedDependencies?: MapLike; } interface TranspileOutput { outputText: string; diff --git a/lib/typescript.js b/lib/typescript.js index 41d3676a415..6babaf9e4a0 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,10 +334,14 @@ 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"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 283] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 287] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; @@ -363,9 +367,9 @@ 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) { @@ -475,6 +479,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) { @@ -559,8 +564,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 +576,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 +587,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 +623,7 @@ var ts; NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var NodeCheckFlags = ts.NodeCheckFlags; (function (TypeFlags) { @@ -625,55 +631,63 @@ 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["FreshObjectLiteral"] = 16777216] = "FreshObjectLiteral"; /* @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"; /* @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) { @@ -893,7 +907,103 @@ var ts; })(ts.CharacterCodes || (ts.CharacterCodes = {})); var CharacterCodes = ts.CharacterCodes; })(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 +1022,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 +1062,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 +1106,36 @@ var ts; return undefined; } ts.forEach = forEach; - function contains(array, value, areEqual) { + /** 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; } } @@ -1024,20 +1176,48 @@ var ts; return count; } ts.countWhere = countWhere; + /** + * Filters an array by a predicate function. Returns the same array instance if the predicate is + * true for all elements, otherwise returns a new array instance containing the filtered subset. + */ 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_3 = array; _i < array_3.length; _i++) { + var item = array_3[_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++) { @@ -1074,11 +1254,15 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + loop: 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); + 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; @@ -1194,117 +1378,191 @@ 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; - function isEmpty(map) { - for (var id in map) { - if (hasProperty(map, id)) { - return false; - } - } - return true; - } - ts.isEmpty = isEmpty; - function clone(object) { - var result = {}; - for (var id in object) { - 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)) { - result[id] = second[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. + * Gets the owned, enumerable property keys of a map-like. * - * @param array the array of input elements. - * @param makeKey a function that produces a key for a given element. + * NOTE: This is intended for use with MapLike objects. For Map objects, use + * Object.keys instead as it offers better performance. * - * 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. + * @param map A map-like. */ - function arrayToMap(array, makeKey) { - var result = {}; - forEach(array, function (value) { - result[makeKey(value)] = value; - }); + 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.arrayToMap = arrayToMap; + 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; /** * 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; - if (map) { - for (var key in map) { - if (hasProperty(map, key)) { - result = callback(result, map[key], String(key)); - } - } + 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_8 = array; _i < array_8.length; _i++) { + var value = array_8[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToMap = arrayToMap; + function cloneMap(map) { + var clone = createMap(); + copyProperties(map, clone); + return clone; + } + ts.cloneMap = cloneMap; + function clone(object) { + var result = {}; + for (var id in object) { + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + 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; /** * Tests whether a value is an array. */ @@ -1329,9 +1587,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) { @@ -1786,10 +2042,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++) { @@ -1814,7 +2085,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += "(/.+?)?"; + subpattern += doubleAsteriskRegexFragment; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -1826,6 +2097,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; } @@ -1846,8 +2130,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); @@ -1966,6 +2256,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) { @@ -2049,9 +2341,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"; } @@ -2275,14 +2571,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(); @@ -2291,23 +2587,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]; - } + (fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback); } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -2319,8 +2610,9 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); + var callbacks = fileWatcherCallbacks[filePath]; + if (callbacks) { + var newCallbacks = ts.copyListRemovingItem(callback, callbacks); if (newCallbacks.length === 0) { delete fileWatcherCallbacks[filePath]; } @@ -2335,7 +2627,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); @@ -3056,6 +3348,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." }, @@ -3103,6 +3396,9 @@ 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." }, 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}'." }, @@ -3173,7 +3469,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}'." }, @@ -3201,6 +3497,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." }, @@ -3321,6 +3618,7 @@ var ts; 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." }, 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." }, @@ -3383,7 +3681,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 */, @@ -3507,7 +3805,7 @@ var ts; "|=": 67 /* BarEqualsToken */, "^=": 68 /* CaretEqualsToken */, "@": 55 /* AtToken */ - }; + }); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -3593,9 +3891,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; } @@ -5083,24 +5379,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; @@ -5118,7 +5396,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -5127,14 +5405,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; } @@ -5156,7 +5434,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; @@ -5290,16 +5568,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); @@ -5994,6 +6276,7 @@ var ts; case 155 /* TypeReference */: return node.typeName; case 194 /* ExpressionWithTypeArguments */: + ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69 /* Identifier */: case 139 /* QualifiedName */: @@ -6459,7 +6742,7 @@ 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; @@ -6506,6 +6789,7 @@ var ts; case 146 /* MethodSignature */: case 225 /* ModuleDeclaration */: case 232 /* NamespaceImport */: + case 228 /* NamespaceExportDeclaration */: case 142 /* Parameter */: case 253 /* PropertyAssignment */: case 145 /* PropertyDeclaration */: @@ -6627,8 +6911,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 */ || @@ -6636,9 +6920,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; @@ -6890,7 +7178,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = {}; + var fileDiagnostics = ts.createMap(); var diagnosticsModified = false; var modificationCount = 0; return { @@ -6904,12 +7192,12 @@ var ts; return modificationCount; } function reattachFileDiagnostics(newFile) { - if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) { - return; - } - for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) { - var diagnostic = _a[_i]; - diagnostic.file = newFile; + var diagnostics = fileDiagnostics[newFile.fileName]; + if (diagnostics) { + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + diagnostic.file = newFile; + } } } function add(diagnostic) { @@ -6943,9 +7231,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); } @@ -6956,9 +7242,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]); } } } @@ -6969,7 +7253,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", @@ -6982,7 +7266,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) @@ -7525,23 +7809,11 @@ var ts; isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - // Returns false if this heritage clause element's expression contains something unsupported - // (i.e. not a name or dotted name). - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 69 /* Identifier */) { - return true; - } - else if (isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } + 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); @@ -7570,6 +7842,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. @@ -7639,7 +7916,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 @@ -7934,7 +8211,6 @@ var ts; /// var ts; (function (ts) { - /* @internal */ ts.parseTime = 0; var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -8064,6 +8340,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); @@ -8342,14 +8620,17 @@ var ts; case 280 /* JSDocPropertyTag */: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); + 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; @@ -8404,7 +8685,7 @@ var ts; var sourceFile; var parseDiagnostics; var syntaxCursor; - var token; + var currentToken; var sourceText; var nodeCount; var identifiers; @@ -8506,7 +8787,7 @@ var ts; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = {}; + identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 134217728 /* JavaScriptFile */ : 0 /* None */; @@ -8532,10 +8813,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; @@ -8729,34 +9010,43 @@ 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 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 @@ -8768,7 +9058,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; } @@ -8791,24 +9081,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(); } @@ -8824,14 +9114,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; @@ -8841,21 +9131,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(); } @@ -8902,7 +9192,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 @@ -8912,8 +9202,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(); @@ -8925,18 +9215,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(); @@ -8948,7 +9238,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]: @@ -8964,7 +9254,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token === t && tryParse(nextTokenCanFollowModifier); + return token() === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -8974,40 +9264,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) { @@ -9025,9 +9315,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 */: @@ -9035,19 +9325,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) { @@ -9062,23 +9352,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 */: @@ -9091,7 +9381,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: @@ -9111,11 +9401,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; @@ -9126,7 +9416,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; } @@ -9139,43 +9429,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() { @@ -9186,14 +9476,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. @@ -9534,7 +9824,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; @@ -9605,7 +9895,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, @@ -9633,7 +9923,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(); } @@ -9643,14 +9933,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); @@ -9683,7 +9970,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); @@ -9731,7 +10018,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 */); } } @@ -9742,7 +10029,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 /* AtToken */ || token === 97 /* ThisKeyword */; + return token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 /* AtToken */ || token() === 97 /* ThisKeyword */; } function setModifiers(node, modifiers) { if (modifiers) { @@ -9752,7 +10039,7 @@ var ts; } 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); @@ -9763,7 +10050,7 @@ var ts; // 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 && node.flags === 0 && ts.isModifierKind(token())) { // in cases like // 'use strict' // function foo(static) @@ -9858,7 +10145,7 @@ var ts; return finishNode(node); } function isIndexSignature() { - if (token !== 19 /* OpenBracketToken */) { + if (token() !== 19 /* OpenBracketToken */) { return false; } return lookAhead(isUnambiguouslyIndexSignature); @@ -9881,10 +10168,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; @@ -9900,18 +10187,18 @@ 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); @@ -9925,7 +10212,7 @@ 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.name = name; @@ -9942,7 +10229,7 @@ var ts; 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. @@ -9955,39 +10242,39 @@ var ts; 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 */ || 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(); @@ -9999,7 +10286,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 */); @@ -10039,10 +10326,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 */: @@ -10054,13 +10350,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 { @@ -10080,7 +10381,7 @@ var ts; } } function isStartOfType() { - switch (token) { + switch (token()) { case 117 /* AnyKeyword */: case 132 /* StringKeyword */: case 130 /* NumberKeyword */: @@ -10097,7 +10398,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. @@ -10108,7 +10414,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token() === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -10122,7 +10428,7 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token === operator) { + if (token() === operator) { var types = [type]; types.pos = type.pos; while (parseOptional(operator)) { @@ -10142,21 +10448,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(); @@ -10166,7 +10472,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token === 18 /* CloseParenToken */ || token === 22 /* DotDotDotToken */) { + if (token() === 18 /* CloseParenToken */ || token() === 22 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -10174,17 +10480,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; } @@ -10207,7 +10513,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -10221,7 +10527,7 @@ var ts; if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156 /* FunctionType */); } - if (token === 92 /* NewKeyword */) { + if (token() === 92 /* NewKeyword */) { return parseFunctionOrConstructorType(157 /* ConstructorType */); } return parseUnionTypeOrHigher(); @@ -10231,7 +10537,7 @@ var ts; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { - switch (token) { + switch (token()) { case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: case 93 /* NullKeyword */: @@ -10259,7 +10565,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token) { + switch (token()) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -10289,10 +10595,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() { @@ -10315,7 +10621,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. @@ -10324,7 +10630,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; @@ -10346,7 +10652,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(); } @@ -10378,7 +10684,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'. @@ -10394,7 +10700,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()) { @@ -10430,7 +10736,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); @@ -10442,7 +10748,7 @@ 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); @@ -10481,7 +10787,7 @@ var ts; var isAsync = !!(arrowFunction.flags & 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) @@ -10493,10 +10799,10 @@ var ts; // 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. @@ -10506,16 +10812,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 */) { @@ -10604,7 +10910,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(); @@ -10618,16 +10924,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 */; } } @@ -10657,19 +10963,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) @@ -10742,16 +11048,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) @@ -10772,13 +11078,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 */: @@ -10835,7 +11141,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185 /* PrefixUnaryExpression */); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -10859,7 +11165,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token === 119 /* AwaitKeyword */) { + if (token() === 119 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -10875,25 +11181,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); @@ -10907,8 +11230,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] @@ -10916,9 +11239,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 */: @@ -10935,6 +11259,10 @@ var ts; // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); + case 119 /* AwaitKeyword */: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } default: return parseIncrementExpression(); } @@ -10942,17 +11270,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 */: @@ -10960,6 +11288,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 @@ -10984,23 +11313,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); } @@ -11037,7 +11366,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 @@ -11097,7 +11426,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 '.'. @@ -11149,7 +11478,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); @@ -11166,11 +11495,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 */: @@ -11178,7 +11507,7 @@ 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 = []; @@ -11186,12 +11515,12 @@ var ts; 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)); @@ -11209,7 +11538,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 @@ -11238,7 +11567,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); @@ -11251,7 +11580,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) { @@ -11264,14 +11593,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) { + switch (token()) { case 9 /* StringLiteral */: node.initializer = parseLiteralNode(); break; @@ -11321,7 +11650,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; @@ -11334,7 +11663,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; @@ -11345,10 +11674,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); @@ -11360,7 +11689,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 @@ -11376,7 +11705,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(); @@ -11408,7 +11737,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. @@ -11444,7 +11773,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token) { + switch (token()) { case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 11 /* NoSubstitutionTemplateLiteral */: @@ -11500,8 +11829,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() { @@ -11539,7 +11868,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 @@ -11547,7 +11876,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; @@ -11615,7 +11944,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); @@ -11695,8 +12024,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 { @@ -11722,11 +12051,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 */); @@ -11778,7 +12107,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 */); @@ -11812,10 +12141,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); } @@ -11858,19 +12187,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 */: @@ -11920,16 +12249,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; @@ -11945,7 +12274,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token) { + switch (token()) { case 55 /* AtToken */: case 23 /* SemicolonToken */: case 15 /* OpenBraceToken */: @@ -11998,7 +12327,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 { @@ -12006,7 +12335,7 @@ var ts; return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token) { + switch (token()) { case 23 /* SemicolonToken */: return parseEmptyStatement(); case 15 /* OpenBraceToken */: @@ -12079,7 +12408,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 */: @@ -12102,7 +12431,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); @@ -12125,10 +12454,10 @@ var ts; } 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; } @@ -12136,7 +12465,7 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token === 24 /* CommaToken */) { + if (token() === 24 /* CommaToken */) { return createNode(193 /* OmittedExpression */); } var node = createNode(169 /* BindingElement */); @@ -12149,7 +12478,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 { @@ -12175,13 +12504,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(); @@ -12190,14 +12519,14 @@ 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 */: @@ -12219,7 +12548,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 { @@ -12304,7 +12633,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 { @@ -12337,12 +12666,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: @@ -12354,17 +12683,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... @@ -12375,7 +12704,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 @@ -12425,8 +12754,8 @@ var ts; 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)) { @@ -12454,9 +12783,9 @@ var ts; 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; @@ -12468,7 +12797,7 @@ var ts; return modifiers; } function parseClassElement() { - if (token === 23 /* SemicolonToken */) { + if (token() === 23 /* SemicolonToken */) { var result = createNode(198 /* SemicolonClassElement */); nextToken(); return finishNode(result); @@ -12480,7 +12809,7 @@ var ts; if (accessor) { return accessor; } - if (token === 121 /* ConstructorKeyword */) { + if (token() === 121 /* ConstructorKeyword */) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { @@ -12488,11 +12817,11 @@ 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) { @@ -12542,7 +12871,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 @@ -12553,9 +12882,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); @@ -12565,13 +12894,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); @@ -12653,7 +12982,7 @@ var ts; var node = createNode(225 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - if (token === 137 /* GlobalKeyword */) { + if (token() === 137 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 131072 /* GlobalAugmentation */; @@ -12661,7 +12990,7 @@ var ts; else { node.name = parseLiteralNode(/*internName*/ true); } - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -12671,7 +13000,7 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (token === 137 /* GlobalKeyword */) { + if (token() === 137 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -12680,14 +13009,14 @@ var ts; } 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() { @@ -12712,7 +13041,7 @@ 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; @@ -12734,8 +13063,8 @@ var ts; // 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 */); } @@ -12760,7 +13089,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); } @@ -12778,7 +13107,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token === 9 /* StringLiteral */) { + if (token() === 9 /* StringLiteral */) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -12825,14 +13154,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(); @@ -12859,7 +13188,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(); } @@ -12997,7 +13326,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token) { + switch (token()) { case 37 /* AsteriskToken */: case 53 /* QuestionToken */: case 17 /* OpenParenToken */: @@ -13010,13 +13339,13 @@ 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 */); scanner.setText(content, start, length); - token = scanner.scan(); + currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -13036,12 +13365,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; @@ -13052,20 +13381,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(); @@ -13078,7 +13407,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token) { + switch (token()) { case 37 /* AsteriskToken */: return parseJSDocAllType(); case 53 /* QuestionToken */: @@ -13105,9 +13434,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() { @@ -13137,7 +13473,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(); } @@ -13154,12 +13490,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; } @@ -13203,7 +13539,7 @@ var ts; function parseJSDocRecordMember() { var result = createNode(266 /* JSDocRecordMember */); result.name = parseSimplePropertyName(); - if (token === 54 /* ColonToken */) { + if (token() === 54 /* ColonToken */) { nextToken(); result.type = parseJSDocType(); } @@ -13252,6 +13588,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 ? @@ -13265,12 +13606,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); } @@ -13290,14 +13631,14 @@ var ts; } 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; @@ -13325,8 +13666,8 @@ var ts; var canParseTag = true; var seenAsterisk = true; nextJSDocToken(); - while (token !== 1 /* EndOfFileToken */) { - switch (token) { + while (token() !== 1 /* EndOfFileToken */) { + switch (token()) { case 55 /* AtToken */: if (canParseTag) { parseTag(); @@ -13371,12 +13712,12 @@ var ts; 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 */); + ts.Debug.assert(token() === 55 /* AtToken */); var atToken = createNode(55 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -13422,7 +13763,7 @@ var ts; } } function tryParseTypeExpression() { - if (token !== 15 /* OpenBraceToken */) { + if (token() !== 15 /* OpenBraceToken */) { return undefined; } var typeExpression = parseJSDocTypeExpression(); @@ -13443,7 +13784,7 @@ var ts; } parseExpected(20 /* CloseBracketToken */); } - else if (ts.tokenIsIdentifierOrKeyword(token)) { + else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); } if (!name) { @@ -13536,9 +13877,9 @@ 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); @@ -13570,7 +13911,7 @@ 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(); @@ -13614,7 +13955,7 @@ var ts; typeParameter.name = name_9; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token === 24 /* CommaToken */) { + if (token() === 24 /* CommaToken */) { nextJSDocToken(); } else { @@ -13630,10 +13971,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) { @@ -13760,8 +14101,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } } @@ -13898,8 +14239,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; visitNode(node); } return; @@ -14132,7 +14473,6 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.bindTime = 0; (function (ModuleInstanceState) { ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; @@ -14204,9 +14544,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() { @@ -14244,7 +14585,7 @@ var ts; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; + classifiableNames = ts.createMap(); symbolCount = 0; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { @@ -14283,10 +14624,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; @@ -14388,7 +14729,10 @@ var ts; // 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 @@ -14400,6 +14744,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. @@ -14407,36 +14756,38 @@ 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 (declaration.flags & 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; @@ -14469,8 +14820,8 @@ var ts; // 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 */)) { 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; @@ -14510,7 +14861,7 @@ var ts; if (containerFlags & 1 /* IsContainer */) { container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { - container.locals = {}; + container.locals = ts.createMap(); } addToContainerChain(container); } @@ -14692,15 +15043,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 */: @@ -14709,9 +15054,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 */: @@ -14733,10 +15077,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 */, @@ -14781,7 +15121,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingSwitchStatement(switchStatement)) { + if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -15419,8 +15759,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; @@ -15429,7 +15769,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 */) { @@ -15477,7 +15817,7 @@ var ts; // fall through. default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; + blockScopeContainer.locals = ts.createMap(); addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -15738,7 +16078,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 */: @@ -15754,7 +16094,7 @@ 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 */; return; @@ -15802,10 +16142,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 */: @@ -15856,18 +16196,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) { @@ -15889,7 +16226,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) { @@ -15925,20 +16262,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. @@ -15957,7 +16299,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 */); @@ -16000,7 +16342,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; } @@ -16167,7 +16509,6 @@ var ts; return node.id; } ts.getNodeId = getNodeId; - ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -16193,7 +16534,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); @@ -16249,32 +16590,39 @@ var ts; 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 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 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. @@ -16318,10 +16666,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 = []; @@ -16362,26 +16708,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 */, @@ -16389,8 +16754,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 */, @@ -16398,17 +16763,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", @@ -16418,10 +16783,10 @@ 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(); // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. var _displayBuilder; var TypeSystemPropertyName; @@ -16431,10 +16796,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) { @@ -16462,13 +16825,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 */) @@ -16482,9 +16845,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; @@ -16505,9 +16868,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; } @@ -16529,12 +16892,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); @@ -16550,28 +16913,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]); } } } @@ -16599,7 +16951,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); @@ -16612,14 +16964,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) { @@ -16634,24 +16984,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. @@ -16760,7 +17112,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 */ || @@ -16814,7 +17166,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; @@ -16850,7 +17202,7 @@ var ts; case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: case 222 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { if (lastLocation && lastLocation.flags & 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 @@ -16880,7 +17232,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; } @@ -16945,8 +17297,9 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -16989,7 +17342,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); @@ -17021,34 +17374,35 @@ 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 false; + 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 checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0); // 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)); } } @@ -17127,7 +17481,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); @@ -17143,9 +17497,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); } } } @@ -17177,6 +17531,10 @@ var ts; // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable); var symbolFromModule = getExportOfModule(targetSymbol, name_10.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_10.text === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; @@ -17196,10 +17554,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) { @@ -17220,7 +17578,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."); @@ -17228,6 +17586,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; @@ -17260,6 +17619,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); @@ -17287,13 +17647,13 @@ 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) { @@ -17306,7 +17666,7 @@ var ts; } var symbol; if (name.kind === 69 /* Identifier */) { - var message = meaning === 1536 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; @@ -17315,7 +17675,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); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -17379,7 +17739,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(moduleReferenceLiteral, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + } } return undefined; } @@ -17418,7 +17785,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] = { @@ -17426,7 +17793,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]; } @@ -17446,12 +17813,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); @@ -17461,7 +17828,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++) { @@ -17516,8 +17883,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) { @@ -17525,6 +17892,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; @@ -17543,14 +17916,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); } } } @@ -17568,7 +17939,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; @@ -17595,7 +17966,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) { @@ -17618,11 +17989,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 */)) { @@ -17653,12 +18024,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; @@ -17705,7 +18076,7 @@ var ts; 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; @@ -17799,11 +18170,11 @@ 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); @@ -17855,6 +18226,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"; @@ -18004,38 +18400,48 @@ var ts; 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) { + 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 */) { + else if (type.flags & 32 /* StringLiteral */) { writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } + else if (type.flags & 64 /* NumberLiteral */) { + writer.writeStringLiteral(type.text); + } else { // Should never get here // { ... } @@ -18061,7 +18467,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 */); @@ -18083,6 +18489,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 @@ -18110,16 +18521,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 */); } @@ -18139,7 +18550,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 @@ -18562,13 +18973,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) { @@ -18586,7 +18997,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); } @@ -18639,7 +19050,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 */) { @@ -18688,7 +19099,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. @@ -18765,7 +19176,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); @@ -18780,7 +19191,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 && 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; @@ -18817,7 +19228,7 @@ 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) { @@ -18865,9 +19276,14 @@ 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); } @@ -18882,7 +19298,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; @@ -18890,23 +19306,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 checkExpressionCached(element.initializer); } 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; @@ -18918,7 +19332,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; }); @@ -18927,24 +19341,24 @@ 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) { 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 e.kind === 193 /* OmittedExpression */ ? 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 @@ -18953,10 +19367,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 @@ -19019,7 +19433,7 @@ var ts; if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var type = undefined; + var type = void 0; // Handle certain special assignment kinds, which happen to union across multiple declarations: // * module.exports = expr // * exports.p = expr @@ -19027,11 +19441,19 @@ var ts; // * className.prototype.method = expr if (declaration.kind === 187 /* BinaryExpression */ || declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) { - type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ? + // Use JS Doc type if present on parent expression statement + if (declaration.flags & 134217728 /* 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); })); + checkExpressionCached(decl.parent.right); }); + type = getUnionType(declaredTypes, /*subtypeReduction*/ true); } - if (type === undefined) { + else { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } if (!popTypeResolution()) { @@ -19128,9 +19550,9 @@ var ts; 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; @@ -19186,7 +19608,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); @@ -19257,7 +19679,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); @@ -19289,7 +19711,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); @@ -19307,25 +19729,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); @@ -19352,7 +19777,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; } @@ -19387,7 +19812,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]; @@ -19422,8 +19847,8 @@ var ts; 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; } @@ -19437,7 +19862,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); @@ -19446,16 +19871,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; } @@ -19470,8 +19895,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); @@ -19482,14 +19908,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; } } @@ -19501,19 +19927,80 @@ 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 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] = createType(256 /* EnumLiteral */); + memberType.symbol = memberSymbol; + memberType.baseType = enumType; + memberType.text = "" + 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; @@ -19537,11 +20024,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); @@ -19574,7 +20064,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); @@ -19625,7 +20115,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; @@ -19635,7 +20125,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); @@ -19645,7 +20135,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; } } @@ -19662,19 +20152,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); @@ -19684,7 +20182,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); @@ -19710,7 +20208,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; @@ -19720,17 +20218,17 @@ 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); @@ -19748,23 +20246,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]; @@ -19819,7 +20300,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 @@ -19845,7 +20326,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 @@ -19910,7 +20391,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)); } @@ -19928,22 +20409,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); } } @@ -19951,7 +20429,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; @@ -19959,13 +20437,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; } } } @@ -19978,7 +20454,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; } } @@ -19986,7 +20462,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 @@ -19995,7 +20471,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); @@ -20008,19 +20484,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; @@ -20029,7 +20505,7 @@ 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]; @@ -20048,7 +20524,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; } @@ -20062,11 +20538,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 */ | @@ -20074,50 +20559,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; } @@ -20131,7 +20620,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; } @@ -20160,7 +20649,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes); + return getUnionType(propTypes, /*subtypeReduction*/ true); } } return undefined; @@ -20245,7 +20734,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; @@ -20268,8 +20757,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) { @@ -20297,6 +20786,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; @@ -20307,7 +20799,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; } @@ -20397,7 +20889,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); @@ -20421,7 +20913,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]; } } @@ -20445,7 +20937,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; @@ -20489,7 +20981,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; } @@ -20521,24 +21013,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 @@ -20552,20 +21047,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)); @@ -20625,8 +21129,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; @@ -20635,7 +21140,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) { @@ -20664,15 +21169,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) : @@ -20713,7 +21218,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; } @@ -20727,7 +21232,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); @@ -20741,8 +21246,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); } /** @@ -20776,16 +21281,46 @@ 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) { @@ -20793,32 +21328,70 @@ var ts; } 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) { + if (type.flags & 524288 /* Union */) { + addTypesToUnion(typeSet, type.types); + } + else if (type.flags & 1 /* Any */) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && type.flags & 6144 /* Nullable */) { + if (type.flags & 2048 /* Undefined */) typeSet.containsUndefined = true; - if (type.flags & 64 /* Null */) + if (type.flags & 4096 /* Null */) typeSet.containsNull = true; - if (!(type.flags & 2097152 /* ContainsWideningType */)) + if (!(type.flags & 33554432 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } - else if (type !== neverType && !ts.contains(typeSet, type)) { - typeSet.push(type); + else if (!(type.flags & 8192 /* Never */)) { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(type.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])) { @@ -20836,14 +21409,14 @@ var ts; } } } - // 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) { + // 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; } @@ -20851,17 +21424,11 @@ 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); } if (typeSet.length === 0) { @@ -20869,84 +21436,112 @@ var ts; 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, getTypeFromTypeNode), /*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, getTypeFromTypeNode), 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 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 = checkExpression(node.literal); } return links.resolvedType; } @@ -20985,7 +21580,7 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node) { + function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { switch (node.kind) { case 117 /* AnyKeyword */: case 258 /* JSDocAllType */: @@ -21007,11 +21602,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); @@ -21028,9 +21631,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 */: @@ -21044,7 +21647,7 @@ var ts; 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 */: @@ -21092,6 +21695,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) { @@ -21124,7 +21728,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; @@ -21162,7 +21766,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; @@ -21199,9 +21803,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; } @@ -21256,10 +21862,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 @@ -21268,20 +21874,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; @@ -21326,10 +21929,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; @@ -21341,26 +21944,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); @@ -21486,8 +22095,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; @@ -21516,6 +22125,73 @@ var ts; sourceNonRestParamCount; } } + function isEnumTypeRelatedTo(source, target, errorReporter) { + if (source === target) { + return true; + } + if (source.symbol.name !== target.symbol.name || !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */)) { + return 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 false; + } + } + } + return 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 */ | 64 /* NumberLiteral */) && target.flags & 16 /* Enum */) + return true; + if (source.flags & 64 /* NumberLiteral */ && target.flags & 256 /* EnumLiteral */ && source.text === target.text) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + 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. @@ -21564,6 +22240,16 @@ 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 @@ -21576,37 +22262,9 @@ var ts; 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 & 16777216 /* FreshObjectLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -21617,24 +22275,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; @@ -21644,7 +22302,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 @@ -21662,13 +22320,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; @@ -21683,7 +22341,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; @@ -21695,9 +22353,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; @@ -21705,14 +22363,17 @@ var ts; } } if (reportErrors) { + if (source.flags & 2588672 /* ObjectType */ && target.flags & 8190 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } 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; @@ -21720,8 +22381,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; @@ -21735,7 +22396,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 || @@ -21744,7 +22405,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)) { @@ -21762,7 +22423,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)) { @@ -21795,18 +22456,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) { @@ -21830,18 +22483,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) { @@ -21921,7 +22566,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = {}; + maybeStack[depth] = ts.createMap(); maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; @@ -21954,7 +22599,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 @@ -21969,7 +22614,7 @@ var ts; } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288 /* ObjectLiteral */); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608 /* ObjectLiteral */); for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -22042,7 +22687,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); @@ -22163,7 +22808,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 */; } @@ -22201,27 +22846,6 @@ 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; @@ -22248,7 +22872,7 @@ 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); @@ -22266,12 +22890,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; @@ -22321,8 +22945,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; @@ -22383,31 +23009,23 @@ 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; - } - return flags; - } function getCommonSupertype(types) { if (!strictNullChecks) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } - 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 */); + 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 @@ -22443,50 +23061,81 @@ 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 isUnitUnionType(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 getBaseTypeOfUnitType(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, getBaseTypeOfUnitType)) : + 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_8 = types; _i < types_8.length; _i++) { + var t = types_8[_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 === emptyStringType ? 32 /* StringLiteral */ : 0 : + type.flags & 64 /* NumberLiteral */ ? type === zeroType ? 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; @@ -22512,7 +23161,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); @@ -22528,7 +23177,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 & 16777216 /* FreshObjectLiteral */)) { return type; } var regularType = type.regularType; @@ -22538,7 +23187,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 /* FreshObjectLiteral */; type.regularType = regularNew; return regularNew; } @@ -22552,24 +23201,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; @@ -22587,7 +23233,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)) { @@ -22595,22 +23241,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))); } @@ -22655,7 +23298,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); @@ -22698,12 +23341,27 @@ var ts; isFixed: false }; } + // 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 inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = {}; + var visited = ts.createMap(); inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -22714,16 +23372,27 @@ 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 + 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 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. var matchingTypes = void 0; - for (var _i = 0, _a = target.types; _i < _a.length; _i++) { - var t = _a[_i]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var t = _c[_b]; if (typeIdenticalToSomeType(t, source.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); @@ -22737,14 +23406,14 @@ 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; @@ -22769,7 +23438,7 @@ var ts; } } } - 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; @@ -22778,22 +23447,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(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -22810,21 +23471,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; } @@ -22832,7 +23489,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (ts.hasProperty(visited, key)) { + if (visited[key]) { return; } visited[key] = true; @@ -22901,8 +23558,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_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -22921,7 +23578,7 @@ 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]; @@ -22934,7 +23591,7 @@ var ts; var inferences = getInferenceCandidates(context, index); if (inferences.length) { // 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(inferences, /*subtypeReduction*/ true) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -23016,10 +23673,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 */: @@ -23031,16 +23684,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; } @@ -23053,6 +23707,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 && + isUnitUnionType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -23079,7 +23775,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++) { @@ -23094,70 +23790,81 @@ 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) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (reducedType !== neverType) { + return reducedType; } } return declaredType; } + function getTypeFactsOfTypes(types) { + var result = 0 /* None */; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_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 === emptyStringType ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : + type === emptyStringType ? 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 === zeroType || type.flags & 256 /* EnumLiteral */ && 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) { @@ -23254,26 +23961,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 = checkExpression(clause.expression); + return isUnitType(caseType) ? caseType : undefined; } - return undefined; + return neverType; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); @@ -23281,26 +23993,56 @@ 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) { return declaredType; @@ -23344,7 +24086,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; } @@ -23369,19 +24111,9 @@ 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)) : + return declaredType.flags & 524288 /* Union */ ? + getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this @@ -23395,32 +24127,43 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var type = getTypeAtFlowNode(flow.antecedent); + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); if (type !== neverType) { // 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 + // 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 reverting to the declared type and then // narrow that. var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType) { + if (type === neverType && isIncomplete(flowType)) { type = narrowType(declaredType, flow.expression, assumeTrue); } } - 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 @@ -23431,14 +24174,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); } @@ -23446,25 +24198,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. @@ -23474,6 +24232,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. @@ -23481,10 +24245,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) { @@ -23494,26 +24285,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 */: @@ -23523,25 +24317,35 @@ 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 (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 !== neverType ? narrowedType : type; + } + return isUnitType(valueType) ? filterType(type, function (t) { return t !== valueType; }) : 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. @@ -23553,72 +24357,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 === neverType ? 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, t)); }); + return caseType === neverType ? 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. @@ -23627,10 +24397,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)) { @@ -23645,13 +24411,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) { @@ -23665,28 +24435,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 !== neverType) { + 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, targetType) ? 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); @@ -23694,6 +24465,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) { @@ -23775,20 +24550,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); @@ -23834,16 +24638,36 @@ var ts; 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); + // 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 || + flowContainer !== declarationContainer || 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; @@ -24051,10 +24875,6 @@ var ts; return getInferredClassType(classSymbol); } } - var type = getContextuallyTypedThisType(container); - if (type) { - return type; - } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -24063,7 +24883,7 @@ 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); + return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*flowContainer*/ undefined); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -24272,11 +25092,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; @@ -24343,7 +25163,7 @@ 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; @@ -24431,6 +25251,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); @@ -24456,14 +25280,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_11 = types; _i < types_11.length; _i++) { + var current = types_11[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -24481,7 +25305,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; }); } @@ -24490,7 +25314,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 @@ -24628,6 +25452,30 @@ var ts; } return undefined; } + function isLiteralTypeLocation(node) { + var parent = node.parent; + switch (parent.kind) { + case 187 /* BinaryExpression */: + switch (parent.operatorToken.kind) { + case 32 /* EqualsEqualsEqualsToken */: + case 33 /* ExclamationEqualsEqualsToken */: + case 30 /* EqualsEqualsToken */: + case 31 /* ExclamationEqualsToken */: + return true; + } + break; + case 188 /* ConditionalExpression */: + return (node === parent.whenTrue || + node === parent.whenFalse) && + isLiteralTypeLocation(parent); + case 178 /* ParenthesizedExpression */: + return isLiteralTypeLocation(parent); + case 249 /* CaseClause */: + case 166 /* LiteralType */: + return true; + } + return false; + } // If the given type is an object or union type, if that type has a single signature, and if // that signature is non-generic, return the signature. Otherwise return undefined. function getNonGenericSignature(type) { @@ -24664,13 +25512,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_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -24766,7 +25614,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; } @@ -24780,7 +25628,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 */) { @@ -24795,7 +25643,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); @@ -24803,7 +25653,7 @@ 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); @@ -24838,7 +25688,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 { @@ -24854,14 +25704,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 && @@ -24901,7 +25751,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); @@ -24948,7 +25798,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); } @@ -24960,8 +25810,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 /* FreshObjectLiteral */; + result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -25028,10 +25878,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 @@ -25122,7 +25971,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; @@ -25138,7 +25987,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 @@ -25147,9 +25996,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 @@ -25180,17 +26029,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) { @@ -25254,7 +26103,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; @@ -25352,7 +26201,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 @@ -25375,7 +26224,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)); } } @@ -25468,12 +26317,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; } @@ -25482,9 +26331,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); @@ -25505,14 +26354,14 @@ var ts; 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)); + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 268435456 /* ThisType */ ? apparentType : type)); } return unknownType; } @@ -25531,15 +26380,18 @@ var ts; checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); + if (prop.flags & 8 /* EnumMember */ && isLiteralContextForType(node, propType)) { + propType = getDeclaredTypeOfSymbol(prop); + } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // 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 isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 /* PropertyAccessExpression */ @@ -25652,9 +26504,10 @@ var ts; } } // 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; @@ -25718,7 +26571,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)); } @@ -25797,7 +26650,7 @@ var ts; 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 @@ -25890,7 +26743,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) { @@ -26024,9 +26877,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; @@ -26211,10 +27062,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 { @@ -26573,8 +27424,8 @@ var ts; // 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))) { + (isTypeAny(apparentType) && funcType.flags & 16384 /* TypeParameter */) || + (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 524288 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { // 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) { @@ -26673,8 +27524,20 @@ var ts; } 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)) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + if (baseTypes.length) { + var baseType = baseTypes[0]; + if (flags & 16 /* Protected */ && + baseType.symbol === declaration.parent.symbol) { + return true; + } + } + } if (flags & 8 /* Private */) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } @@ -26693,7 +27556,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 524288 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -26730,7 +27593,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 524288 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); @@ -26853,7 +27716,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; @@ -26865,6 +27728,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); @@ -27004,7 +27873,7 @@ var ts; } // 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); + type = contextualSignature ? getUnionType(types, /*subtypeReduction*/ true) : getCommonSupertype(types); if (!type) { if (funcIsGenerator) { error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); @@ -27013,7 +27882,7 @@ var ts; 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 isAsync ? createPromiseReturnType(func, getUnionType(types, /*subtypeReduction*/ true)) : getUnionType(types, /*subtypeReduction*/ true); } } if (funcIsGenerator) { @@ -27047,24 +27916,18 @@ 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 (!isUnitUnionType(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 */)) { @@ -27128,7 +27991,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. @@ -27257,7 +28120,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -27369,16 +28232,22 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (node.operator === 36 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */ && isLiteralContextForType(node, numberType)) { + return 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); @@ -27405,10 +28274,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_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -27423,20 +28292,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_14 = types; _i < types_14.length; _i++) { + var t = types_14[_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_15 = types; _a < types_15.length; _a++) { + var t = types_15[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -27445,7 +28314,7 @@ 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; @@ -27456,7 +28325,7 @@ var ts; // 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 @@ -27470,10 +28339,10 @@ var ts; // 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; @@ -27544,8 +28413,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); @@ -27577,7 +28449,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); @@ -27607,7 +28479,14 @@ var ts; return sourceType; } 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); @@ -27648,17 +28527,17 @@ var ts; // 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)); } @@ -27677,20 +28556,20 @@ var ts; // 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; } @@ -27726,6 +28605,12 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: + var leftIsUnit = isUnitUnionType(leftType); + var rightIsUnit = isUnitUnionType(rightType); + if (!leftIsUnit || !rightIsUnit) { + leftType = leftIsUnit ? getBaseTypeOfUnitType(leftType) : leftType; + rightType = rightIsUnit ? getBaseTypeOfUnitType(rightType) : rightType; + } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -27735,9 +28620,13 @@ 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 : getBaseTypeOfUnitType(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); @@ -27746,8 +28635,8 @@ var ts; } // 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)); @@ -27847,14 +28736,66 @@ 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 typeContainsLiteralFromEnum(type, enumType) { + if (type.flags & 524288 /* Union */) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 256 /* EnumLiteral */ && t.baseType === enumType) { + return true; + } + } + } + if (type.flags & 256 /* EnumLiteral */) { + return type.baseType === enumType; + } + return false; + } + function isLiteralContextForType(node, type) { + if (isLiteralTypeLocation(node)) { + return true; + } + var contextualType = getContextualType(node); + 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 (type === apparentType) { + return true; + } + contextualType = apparentType; + } + if (type.flags & 2 /* String */) { + return maybeTypeOfKind(contextualType, 32 /* StringLiteral */); + } + if (type.flags & 4 /* Number */) { + return maybeTypeOfKind(contextualType, (64 /* NumberLiteral */ | 256 /* EnumLiteral */)); + } + if (type.flags & 8 /* Boolean */) { + return maybeTypeOfKind(contextualType, 128 /* BooleanLiteral */) && !isTypeAssignableTo(booleanType, contextualType); + } + if (type.flags & 16 /* Enum */) { + return typeContainsLiteralFromEnum(contextualType, type); + } + } + return false; + } + function checkLiteralExpression(node) { + if (node.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9 /* StringLiteral */: + return isLiteralContextForType(node, stringType) ? getLiteralTypeForText(32 /* StringLiteral */, node.text) : stringType; + case 8 /* NumericLiteral */: + return isLiteralContextForType(node, numberType) ? getLiteralTypeForText(64 /* NumberLiteral */, node.text) : numberType; + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + return isLiteralContextForType(node, booleanType) ? node.kind === 99 /* TrueKeyword */ ? trueType : falseType : booleanType; } - return stringType; } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with @@ -27953,11 +28894,6 @@ var ts; } return type; } - function checkNumericLiteral(node) { - // Grammar checking - checkGrammarNumericLiteral(node); - return numberType; - } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69 /* Identifier */: @@ -27968,15 +28904,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 */: @@ -28231,16 +29165,21 @@ var ts; } } 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 */); } } } @@ -28251,21 +29190,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)); } @@ -28279,7 +29218,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 */) { @@ -28293,7 +29232,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); } @@ -28460,12 +29399,7 @@ var ts; 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 (!(node.flags & 65536 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -28494,7 +29428,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); @@ -28548,6 +29485,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) { @@ -28855,10 +29795,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 */; } @@ -28895,7 +29835,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]; @@ -28921,7 +29861,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; @@ -28939,13 +29879,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); @@ -29167,7 +30107,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 @@ -29357,22 +30297,20 @@ 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) && - !parameterIsThisKeyword(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 /* 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) { @@ -29400,7 +30338,7 @@ var ts; 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); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -29430,14 +30368,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); } } } @@ -29926,7 +30862,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 { @@ -29937,7 +30873,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); @@ -30019,7 +30955,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 { @@ -30034,7 +30970,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; @@ -30060,7 +30996,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 { @@ -30075,7 +31011,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; } @@ -30097,7 +31033,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) || @@ -30125,10 +31061,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; @@ -30160,10 +31096,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; } @@ -30177,7 +31113,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 @@ -30329,7 +31265,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); @@ -30354,7 +31290,7 @@ 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]; @@ -30373,7 +31309,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]; } @@ -30398,7 +31334,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 @@ -30513,6 +31449,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 @@ -30530,15 +31471,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 { @@ -30692,7 +31633,7 @@ 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++) { @@ -30700,11 +31641,11 @@ var ts; 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)) { + 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; @@ -30745,7 +31686,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); @@ -31106,10 +32047,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)) { @@ -31171,19 +32108,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); @@ -31223,8 +32161,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 : @@ -31281,11 +32219,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); } } @@ -31335,7 +32273,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); @@ -31405,7 +32343,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); @@ -31588,9 +32526,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) { @@ -31670,7 +32609,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = {}; + var symbols = ts.createMap(); var memberFlags = 0; if (isInsideWithStatementBody(location)) { // We cannot answer semantic questions within a with block, do not proceed any further @@ -31708,7 +32647,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 */: @@ -31739,7 +32678,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; } } @@ -31828,17 +32767,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; @@ -31847,14 +32784,14 @@ 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); @@ -31886,7 +32823,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 */) { @@ -31990,7 +32927,7 @@ 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)) { @@ -32104,7 +33041,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; } }); @@ -32155,7 +33092,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) { @@ -32343,7 +33280,7 @@ 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) { // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. @@ -32353,7 +33290,7 @@ var ts; 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); // 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; @@ -32365,22 +33302,22 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 16 /* Void */)) { + else if (isTypeOfKind(type, 1024 /* Void */)) { return ts.TypeReferenceSerializationKind.VoidType; } - 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)) { @@ -32416,7 +33353,7 @@ 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 || @@ -32437,9 +33374,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; @@ -32488,7 +33422,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; } @@ -32608,7 +33542,7 @@ 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"); }); @@ -32628,7 +33562,7 @@ 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; } @@ -32643,7 +33577,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 = []; @@ -32672,49 +33606,9 @@ 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; @@ -32908,6 +33802,60 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } + /** + * 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) { if (languageVersion < 2 /* ES6 */) { return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); @@ -33145,7 +34093,7 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = {}; + var seen = ts.createMap(); var Property = 1; var GetAccessor = 2; var SetAccessor = 4; @@ -33201,7 +34149,7 @@ var ts; if (effectiveName === undefined) { return "continue"; } - if (!ts.hasProperty(seen, effectiveName)) { + if (!seen[effectiveName]) { seen[effectiveName] = currentKind; } else { @@ -33229,7 +34177,7 @@ var ts; } } 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 */) { @@ -33237,7 +34185,7 @@ var ts; } var jsxAttr = attr; var name_22 = jsxAttr.name; - if (!ts.hasProperty(seen, name_22.text)) { + if (!seen[name_22.text]) { seen[name_22.text] = true; } else { @@ -33587,7 +34535,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: @@ -33605,6 +34553,7 @@ var ts; node.kind === 229 /* ImportEqualsDeclaration */ || node.kind === 236 /* ExportDeclaration */ || node.kind === 235 /* ExportAssignment */ || + node.kind === 228 /* NamespaceExportDeclaration */ || (node.flags & 2 /* Ambient */) || (node.flags & (1 /* Export */ | 512 /* Default */))) { return false; @@ -33665,7 +34614,6 @@ var ts; return true; } } - var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -33702,6 +34650,7 @@ var ts; ts.getNullSourceMapWriter = getNullSourceMapWriter; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var sourceMapDir; // The directory in which sourcemap will be var stopOverridingSpan = false; @@ -33865,6 +34814,9 @@ var ts; if (pos === -1) { return; } + if (extendedDiagnostics) { + ts.performance.mark("beforeSourcemap"); + } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); // Convert the location to be one-based. sourceLinePos.line++; @@ -33897,6 +34849,10 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); + if (extendedDiagnostics) { + ts.performance.mark("afterSourcemap"); + ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); + } } function getStartPos(range) { var rangeHasDecorators = !!range.decorators; @@ -34104,9 +35060,7 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { - referencesOutput += "/// " + newLine; - } + referencesOutput += "/// " + newLine; } } return { @@ -34204,11 +35158,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; } } @@ -34316,7 +35270,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); @@ -34367,7 +35321,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) { @@ -34441,14 +35395,14 @@ 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)) { + if (!(name_23 in currentIdentifiers)) { return name_23; } } @@ -34881,7 +35835,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 */) { @@ -34987,8 +35941,10 @@ 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 */) { @@ -35603,7 +36559,7 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); - var entities = { + var entities = ts.createMap({ "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -35857,7 +36813,7 @@ var ts; "clubs": 0x2663, "hearts": 0x2665, "diams": 0x2666 - }; + }); // Flags enum to track count of temp variables and a few dedicated names var TempFlags; (function (TempFlags) { @@ -35900,7 +36856,7 @@ var ts; }; 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 in node.locals) { // 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; @@ -35912,13 +36868,13 @@ var ts; function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = {}; + state.labeledNonLocalBreaks = ts.createMap(); } state.labeledNonLocalBreaks[labelText] = labelMarker; } else { if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = {}; + state.labeledNonLocalContinues = ts.createMap(); } state.labeledNonLocalContinues[labelText] = labelMarker; } @@ -35985,26 +36941,26 @@ var ts; /** 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 = {}, + var moduleEmitDelegates = ts.createMap((_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 = {}, + )); + var bundleEmitDelegates = ts.createMap((_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 = {}; + generatedNameSet = ts.createMap(); nodeToGeneratedName = []; decoratedClassAliases = []; isOwnFileEmit = !isBundledEmit; @@ -36066,8 +37022,8 @@ var ts; } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentFileIdentifiers, name) && - !ts.hasProperty(generatedNameSet, name); + !(name in currentFileIdentifiers) && + !(name in generatedNameSet); } // 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. @@ -37093,6 +38049,10 @@ var ts; else if (node.parent.kind === 188 /* ConditionalExpression */ && node.parent.condition === node) { return true; } + else if (node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 181 /* DeleteExpression */ || + node.parent.kind === 182 /* TypeOfExpression */ || node.parent.kind === 183 /* VoidExpression */) { + return true; + } return false; } function needsParenthesisForPropertyAccessOrInvocation(node) { @@ -37766,7 +38726,7 @@ var ts; operand.kind === 196 /* NonNullExpression */) { operand = operand.expression; } - // We have an expression of the form: (SubExpr) + // We have an expression of the form: (SubExpr) or (SubExpr as Type) // 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.: @@ -37780,6 +38740,7 @@ var ts; operand.kind !== 181 /* DeleteExpression */ && operand.kind !== 186 /* PostfixUnaryExpression */ && operand.kind !== 175 /* NewExpression */ && + !(operand.kind === 187 /* BinaryExpression */ && node.expression.kind === 195 /* AsExpression */) && !(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 */)) { @@ -37821,7 +38782,7 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); + return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 /* PlusPlusToken */ @@ -38366,12 +39327,12 @@ var ts; // 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 = {}; + seen = ts.createMap(); } else { write(", "); } - if (!ts.hasProperty(seen, id.text)) { + if (!(id.text in seen)) { emit(id); seen[id.text] = id.text; } @@ -38895,7 +39856,7 @@ var ts; } if (convertedLoopState) { if (!convertedLoopState.labels) { - convertedLoopState.labels = {}; + convertedLoopState.labels = ts.createMap(); } convertedLoopState.labels[node.label.text] = node.label.text; } @@ -38998,7 +39959,7 @@ var ts; if (modulekind === ts.ModuleKind.System) { return; } - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + if (!exportEquals && exportSpecifiers && name.text in exportSpecifiers) { for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { var specifier = _b[_a]; writeLine(); @@ -39536,12 +40497,13 @@ var ts; } function emitRestParameter(node) { if (languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; + var restParam = node.parameters[node.parameters.length - 1]; // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. if (ts.isBindingPattern(restParam.name)) { return; } + var skipThisCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; + var restIndex = node.parameters.length - 1 - skipThisCount; var tempName = createTempVariable(268435456 /* _i */).text; writeLine(); emitLeadingComments(restParam); @@ -39676,7 +40638,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; + var skipCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; var omitCount = languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node) ? 1 : 0; emitList(parameters, skipCount, parameters.length - omitCount - skipCount, /*multiLine*/ false, /*trailingComma*/ false); } @@ -40198,18 +41160,22 @@ var ts; 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. + // 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 String "constructor( ){ }" using the syntactic grammar with the goal symbol MethodDefinition - if (baseTypeElement) { - write("(...args)"); - } - else { - write("()"); - } + // 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 below. + write("()"); } } var startIndex = 0; @@ -40243,7 +41209,8 @@ var ts; write("_super.apply(this, arguments);"); } else { - write("super(...args);"); + // See comment above on using '...arguments' instead of '...args'. + write("super(...arguments);"); } emitEnd(baseTypeElement); } @@ -40402,13 +41369,17 @@ var ts; // 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; ... } + // (class C { static a = 1; static b = 2; ... }) // // We'll emit: // - // let C_1 = class C{}; - // C_1.a = 1; - // C_1.b = 2; // so forth and so on + // ((C_1 = class C { + // // Normal class body + // }, + // C_1.a = 1, + // C_1.b = 2, + // C_1)); + // var C_1; // // This keeps the expression as an expression, while ensuring that the static parts // of it have been initialized by the time it is used. @@ -40416,7 +41387,7 @@ var ts; var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192 /* ClassExpression */; var generatedName; if (isClassExpressionWithStaticProperties) { - generatedName = getGeneratedNameForNode(node.name); + generatedName = node.name ? getGeneratedNameForNode(node.name) : makeUniqueName("classExpression"); var synthesizedNode = ts.createSynthesizedNode(69 /* Identifier */); synthesizedNode.text = generatedName; recordTempDeclaration(synthesizedNode); @@ -40861,7 +41832,7 @@ var ts; write("Boolean"); return; case 132 /* StringKeyword */: - case 166 /* StringLiteralType */: + case 166 /* LiteralType */: write("String"); return; case 130 /* NumberKeyword */: @@ -40959,10 +41930,11 @@ var ts; } if (valueDeclaration) { var parameters = valueDeclaration.parameters; + var skipThisCount = parameters.length && parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; var parameterCount = parameters.length; - if (parameterCount > 0) { - for (var i = 0; i < parameterCount; i++) { - if (i > 0) { + if (parameterCount > skipThisCount) { + for (var i = skipThisCount; i < parameterCount; i++) { + if (i > skipThisCount) { write(", "); } if (parameters[i].dotDotDotToken) { @@ -41230,7 +42202,7 @@ var ts; * 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)) { + if (renamedDependencies && moduleName.text in renamedDependencies) { return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; @@ -41550,7 +42522,7 @@ var ts; } function collectExternalModuleInfo(sourceFile) { externalImports = []; - exportSpecifiers = {}; + exportSpecifiers = ts.createMap(); exportEquals = undefined; hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { @@ -41678,7 +42650,7 @@ var ts; return undefined; } // local names set should only be added if we have anything exported - if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { + if (!exportedDeclarations && !ts.someProperties(exportSpecifiers)) { // no exported declarations (export var ...) or export specifiers (export {x}) // check if we have any non star export declarations. var hasExportDeclarationWithExportClause = false; @@ -41801,7 +42773,7 @@ var ts; if (hoistedVars) { writeLine(); write("var "); - var seen = {}; + var seen = ts.createMap(); for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; var name_32 = local.kind === 69 /* Identifier */ @@ -41810,7 +42782,7 @@ var ts; 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)) { + if (text in seen) { continue; } else { @@ -42126,7 +43098,7 @@ var ts; write("System.register("); writeModuleName(node, emitRelativePathAsModuleName); write("["); - var groupIndices = {}; + var groupIndices = ts.createMap(); var dependencyGroups = []; for (var i = 0; i < externalImports.length; i++) { var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); @@ -42136,7 +43108,7 @@ var ts; // 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)) { + if (key in groupIndices) { // deduplicate/group entries in dependency list by the dependency name var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); @@ -42967,12 +43939,8 @@ var 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.1.0"; + ts.version = "2.0.2"; var emptyArray = []; var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { @@ -43064,46 +44032,26 @@ var ts; 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 @@ -43116,6 +44064,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) { @@ -43412,7 +44370,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); @@ -43557,22 +44515,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); @@ -43580,29 +44540,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) { @@ -43610,7 +44569,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; } @@ -43630,6 +44592,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); @@ -43705,15 +44670,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. @@ -43724,9 +44682,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) { @@ -43739,7 +44698,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)) { @@ -43758,11 +44717,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 && @@ -43781,7 +44740,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); @@ -43789,7 +44748,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) { @@ -43830,8 +44790,8 @@ var ts; 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]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; if (diagnostic.file) { var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; var fileName = diagnostic.file.fileName; @@ -43872,33 +44832,25 @@ var ts; return []; } var resolutions = []; - var cache = {}; + var cache = ts.createMap(); 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 result = name_34 in cache + ? cache[name_34] + : cache[name_34] = loader(name_34, 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; @@ -43911,7 +44863,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)); + } + } } } } @@ -43926,7 +44888,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: @@ -43935,14 +44897,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 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 = {}; + 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 = {}; - var start = new Date().getTime(); + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -43973,10 +44935,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]); @@ -44027,7 +44989,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") { @@ -44051,10 +45014,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; @@ -44079,7 +45042,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); @@ -44185,7 +45148,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 }; @@ -44233,9 +45196,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) { @@ -44387,16 +45351,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) { @@ -44440,8 +45404,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; @@ -44651,7 +45615,7 @@ var ts; } // 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 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) { + if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { sourceFilesFoundSearchingNodeModules[file_1.path] = false; if (!options.noResolve) { processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); @@ -44660,7 +45624,7 @@ var ts; modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } - else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { + else if (file_1 && modulesWithElidedImports[file_1.path]) { if (currentNodeModulesDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); @@ -44715,14 +45679,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) { @@ -44743,7 +45709,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; @@ -44779,7 +45745,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++) { @@ -44878,6 +45844,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; @@ -44924,7 +45893,7 @@ 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)); @@ -44935,19 +45904,19 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.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 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.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 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.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 @@ -45036,6 +46005,10 @@ var ts; name: "diagnostics", type: "boolean" }, + { + name: "extendedDiagnostics", + type: "boolean" + }, { name: "emitBOM", type: "boolean" @@ -45066,10 +46039,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 }, @@ -45096,7 +46069,7 @@ var ts; { name: "module", shortName: "m", - type: { + type: ts.createMap({ "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -45104,16 +46077,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 }, @@ -45131,6 +46104,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", @@ -45255,12 +46232,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 }, @@ -45289,10 +46266,10 @@ 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 }, { @@ -45397,7 +46374,7 @@ var ts; type: "list", element: { name: "lib", - type: { + type: ts.createMap({ // JavaScript only "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", @@ -45422,7 +46399,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 }, @@ -45459,14 +46436,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) { @@ -45480,9 +46464,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; @@ -45490,7 +46474,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 { @@ -45542,10 +46526,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)); @@ -45657,6 +46641,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_35 in options) { + if (ts.hasProperty(options, name_35)) { + // 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_35) { + case "init": + case "watch": + case "version": + case "help": + case "project": + break; + default: + var value = options[name_35]; + var optionDefinition = optionsNameMap[name_35.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_35] = 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_35] = convertedValue; + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result[name_35] = 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 / * * / @@ -45681,9 +46749,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 @@ -45767,7 +46832,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; } @@ -45784,7 +46849,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); } @@ -45819,7 +46884,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 { @@ -45919,11 +46984,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); } @@ -45959,16 +47024,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; } } @@ -46017,20 +47079,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_36 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_36)) { continue; } - var match = wildcardDirectoryPattern.exec(name_35); + var match = wildcardDirectoryPattern.exec(name_36); 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_36) ? 1 /* Recursive */ : 0 /* None */; + var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1 /* Recursive */) { @@ -46041,12 +47103,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]; } } } @@ -46067,7 +47127,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; } } @@ -46293,12 +47353,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_36 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_36); + for (var name_37 in nameToDeclarations) { + var declarations = nameToDeclarations[name_37]; 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_37); if (!matches) { continue; } @@ -46311,14 +47371,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_36); + matches = patternMatcher.getMatches(containers, name_37); 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_37, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -46600,9 +47660,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_38 = decl.name; + if (ts.isBindingPattern(name_38)) { + addChildrenRecursively(name_38); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { // For `const x = function() {}`, just use the function node, not the const. @@ -46665,7 +47725,7 @@ var ts; } /** 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); @@ -46673,7 +47733,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; @@ -46916,7 +47976,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, @@ -46927,7 +47987,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, @@ -46947,49 +48007,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)) { @@ -47069,7 +48086,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); @@ -47125,7 +48142,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!ts.hasProperty(stringToWordSpans, word)) { + if (!(word in stringToWordSpans)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -47797,7 +48814,7 @@ 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]; @@ -48354,7 +49371,7 @@ var ts; // 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) { + if (c.kind === 286 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -48548,8 +49565,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && - (previousToken.kind === 9 /* StringLiteral */ || previousToken.kind === 166 /* StringLiteralType */)) { + 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: @@ -48732,7 +49748,6 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 /* StringLiteral */ - || kind === 166 /* StringLiteralType */ || kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; @@ -49036,12 +50051,34 @@ var ts; if (host && host.getScriptKind) { scriptKind = host.getScriptKind(fileName); } - if (!scriptKind || scriptKind === 0 /* Unknown */) { + 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_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; + diagnostic.start = diagnostic.start - 1; + } + return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + } + ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; })(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. @@ -49067,7 +50104,7 @@ var ts; */ function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { // A typing name to typing file path mapping - var inferredTypings = {}; + var inferredTypings = ts.createMap(); if (!typingOptions || !typingOptions.enableAutoDiscovery) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } @@ -49075,13 +50112,7 @@ var ts; 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 = {}; - } - ; + safeList = ts.createMap(result.config); } var filesToWatch = []; // Directories to search for package.json, bower.json and other typing information @@ -49106,7 +50137,7 @@ var ts; 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]) { + if (name_39 in inferredTypings && !inferredTypings[name_39]) { inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } @@ -49135,7 +50166,7 @@ var ts; } for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { var typing = typingNames_1[_i]; - if (!ts.hasProperty(inferredTypings, typing)) { + if (!(typing in inferredTypings)) { inferredTypings[typing] = undefined; } } @@ -49149,16 +50180,16 @@ var ts; var jsonConfig = result.config; filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { - mergeTypings(ts.getKeys(jsonConfig.dependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } if (jsonConfig.devDependencies) { - mergeTypings(ts.getKeys(jsonConfig.devDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); } if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); } if (jsonConfig.peerDependencies) { - mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); } } } @@ -49176,7 +50207,7 @@ var ts; mergeTypings(cleanedTypingNames); } else { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); + 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) { @@ -49806,7 +50837,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() {} @@ -49853,6 +50884,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, @@ -49880,6 +50917,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, @@ -49913,8 +50952,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 */)); @@ -49951,10 +50990,10 @@ 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 */)); @@ -50166,12 +51205,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); }; @@ -50974,8 +52022,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; @@ -52144,7 +53193,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 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++) { @@ -52167,13 +53216,16 @@ var 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) { @@ -52642,7 +53694,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; }; @@ -52701,7 +53753,7 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = {}; + var result = ts.createMap(); ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { @@ -52712,13 +53764,13 @@ var ts; } } 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_3 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_3 !== undefined) { + return result_3; } if (declaration.name.kind === 140 /* ComputedPropertyName */) { var expr = declaration.name.expression; @@ -52932,6 +53984,8 @@ var ts; ScriptElementKind.typeElement = "type"; /** enum E */ ScriptElementKind.enumElement = "enum"; + // TODO: GH#9983 + ScriptElementKind.enumMemberElement = "const"; /** * Inside module and script only * const v = .. @@ -53078,7 +54132,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 () { @@ -53190,7 +54244,7 @@ var ts; 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"; }); + return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); var _loop_3 = function(opt) { @@ -53204,7 +54258,7 @@ var ts; options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); } else { - if (!ts.forEachValue(opt.type, function (v) { return v === value; })) { + if (!ts.forEachProperty(opt.type, function (v) { return v === value; })) { // Supplied value isn't a valid enum value. diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); } @@ -53256,7 +54310,9 @@ var ts; if (transpileOptions.moduleName) { sourceFile.moduleName = transpileOptions.moduleName; } - sourceFile.renamedDependencies = transpileOptions.renamedDependencies; + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMap(transpileOptions.renamedDependencies); + } var newLine = ts.getNewLineCharacter(options); // Output var outputText; @@ -53367,13 +54423,13 @@ var ts; 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 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 = ts.lookUp(buckets, key); + var bucket = buckets[key]; if (!bucket && createIfMissing) { buckets[key] = bucket = ts.createFileMap(); } @@ -53381,7 +54437,7 @@ var ts; } 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 entries = buckets[name]; var sourceFiles = []; entries.forEachValue(function (key, entry) { sourceFiles.push({ @@ -53997,7 +55053,10 @@ var ts; ts.getContainerNode = getContainerNode; /* @internal */ function getNodeKind(node) { switch (node.kind) { - case 225 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; + case 256 /* SourceFile */: + return ts.isExternalModule(node) ? ScriptElementKind.moduleElement : ScriptElementKind.scriptElement; + case 225 /* ModuleDeclaration */: + return ScriptElementKind.moduleElement; case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: return ScriptElementKind.classElement; @@ -54005,11 +55064,10 @@ var ts; 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; + return getKindOfVariableDeclaration(node); + case 169 /* BindingElement */: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 180 /* ArrowFunction */: case 220 /* FunctionDeclaration */: case 179 /* FunctionExpression */: return ScriptElementKind.functionElement; @@ -54026,7 +55084,7 @@ var ts; 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 255 /* EnumMember */: return ScriptElementKind.enumMemberElement; case 142 /* Parameter */: return (node.flags & 92 /* ParameterPropertyModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; case 229 /* ImportEqualsDeclaration */: case 234 /* ImportSpecifier */: @@ -54034,8 +55092,18 @@ var ts; case 238 /* ExportSpecifier */: case 232 /* NamespaceImport */: return ScriptElementKind.alias; + case 279 /* JSDocTypedefTag */: + return ScriptElementKind.typeElement; + default: + return ScriptElementKind.unknown; + } + function getKindOfVariableDeclaration(v) { + return ts.isConst(v) + ? ScriptElementKind.constElement + : ts.isLet(v) + ? ScriptElementKind.letElement + : ScriptElementKind.variableElement; } - return ScriptElementKind.unknown; } ts.getNodeKind = getNodeKind; var CancellationTokenObject = (function () { @@ -54110,14 +55178,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, @@ -54131,7 +55201,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) { @@ -54166,7 +55235,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); } } @@ -54194,7 +55263,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) { @@ -54307,7 +55376,7 @@ var ts; 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 ((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; @@ -54343,13 +55412,13 @@ var ts; var sourceFile = getValidSourceFile(fileName); var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var isJsDocTagName = false; - var start = new Date().getTime(); + var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); - log("getCompletionData: Get current token: " + (new Date().getTime() - start)); - start = new Date().getTime(); + 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 = isInsideComment(sourceFile, currentToken, position); - log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); + 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 @@ -54386,18 +55455,18 @@ var ts; return undefined; } } - start = new Date().getTime(); + start = ts.timestamp(); var previousToken = ts.findPrecedingToken(position, sourceFile); - log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); + 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_5 = new Date().getTime(); + var start_2 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); + 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 @@ -54440,7 +55509,7 @@ var ts; } } } - var semanticStart = new Date().getTime(); + var semanticStart = ts.timestamp(); var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -54475,7 +55544,7 @@ var ts; return undefined; } } - log("getCompletionData: Semantic work: " + (new Date().getTime() - semanticStart)); + 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 @@ -54509,7 +55578,7 @@ var ts; symbols.push(symbol); } } - if (isJavaScriptFile && type.flags & 16384 /* Union */) { + 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 @@ -54584,7 +55653,7 @@ var ts; 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 */; + var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 8388608 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); return true; } @@ -54600,12 +55669,12 @@ var ts; return scope; } function isCompletionListBlocker(contextToken) { - var start = new Date().getTime(); + var start = ts.timestamp(); var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || isSolelyIdentifierDefinitionLocation(contextToken) || isDotOfNumericLiteral(contextToken) || isInJsxText(contextToken); - log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); return result; } function isInJsxText(contextToken) { @@ -54674,16 +55743,15 @@ var ts; } 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 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_6 < position && position < end) { + if (start_3 < position && position < end) { return true; } if (position === end) { @@ -54708,7 +55776,10 @@ var ts; // 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 */) { @@ -54719,7 +55790,7 @@ var ts; // 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 - + // 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 */) { @@ -54984,7 +56055,7 @@ var ts; * do not occur at the current position and have not otherwise been typed. */ function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = {}; + 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 @@ -54994,10 +56065,10 @@ var ts; var name_41 = element.propertyName || element.name; existingImportsOrExports[name_41.text] = true; } - if (ts.isEmpty(existingImportsOrExports)) { + if (!ts.someProperties(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); }); + return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; }); } /** * Filters out completion suggestions for named imports or exports. @@ -55009,7 +56080,7 @@ var ts; if (!existingMembers || existingMembers.length === 0) { return contextualMemberSymbols; } - var existingMemberNames = {}; + 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 @@ -55038,7 +56109,7 @@ var ts; } existingMemberNames[existingName] = true; } - return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames[m.name]; }); } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. @@ -55047,7 +56118,7 @@ var ts; * do not occur at the current position and have not otherwise been typed. */ function filterJsxAttributes(symbols, attributes) { - var seenNames = {}; + 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 @@ -55058,7 +56129,7 @@ var ts; seenNames[attr.name.text] = true; } } - return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); + return ts.filter(symbols, function (a) { return !seenNames[a.name]; }); } } function getCompletionsAtPosition(fileName, position) { @@ -55107,7 +56178,7 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var target = program.getCompilerOptions().target; @@ -55166,22 +56237,22 @@ var ts; }; } function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { - var start = new Date().getTime(); - var uniqueNames = {}; + 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 (!ts.lookUp(uniqueNames, id)) { + if (!uniqueNames[id]) { entries.push(entry); uniqueNames[id] = id; } } } } - log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniqueNames; } function getStringLiteralCompletionEntries(sourceFile, position) { @@ -55189,21 +56260,55 @@ var ts; 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); + 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 { - // Otherwise, get the completions from the contextual type if one exists + 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 getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element) { + var typeChecker = program.getTypeChecker(); + 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 typeChecker = program.getTypeChecker(); var candidates = []; var entries = []; @@ -55248,11 +56353,11 @@ var ts; if (!type) { return; } - if (type.flags & 16384 /* Union */) { + if (type.flags & 524288 /* Union */) { ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); } else { - if (type.flags & 256 /* StringLiteral */) { + if (type.flags & 32 /* StringLiteral */) { result.push({ name: type.text, kindModifiers: ScriptElementKindModifier.none, @@ -55471,7 +56576,7 @@ var ts; displayParts.push(ts.keywordPart(92 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 65536 /* Anonymous */) && type.symbol) { + 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 */); @@ -55540,7 +56645,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(56 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { addNewLineIfDisplayPartsExist(); @@ -55619,7 +56724,14 @@ var ts; } if (symbolFlags & 8388608 /* Alias */) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); + 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) { @@ -55692,6 +56804,27 @@ var ts; } 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 = program.getTypeChecker().getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(); + if (documentation.length > 0) { + break; + } + } + } + } } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; function addNewLineIfDisplayPartsExist() { @@ -55898,7 +57031,7 @@ var ts; // Type reference directives var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { - var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); + var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; if (referenceFile && referenceFile.resolvedFileName) { return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } @@ -55973,14 +57106,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 16384 /* Union */) { - var result_3 = []; + if (type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */)) { + var result_4 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_3, /*from*/ getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(/*to*/ result_4, /*from*/ getDefinitionFromSymbol(t.symbol, node)); } }); - return result_3; + return result_4; } if (!type.symbol) { return undefined; @@ -56030,14 +57163,14 @@ var ts; if (!referencedSymbols) { return undefined; } - var fileNameToDocumentHighlights = {}; + var fileNameToDocumentHighlights = ts.createMap(); 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); + var documentHighlights = fileNameToDocumentHighlights[fileName_1]; if (!documentHighlights) { documentHighlights = { fileName: fileName_1, highlightSpans: [] }; fileNameToDocumentHighlights[fileName_1] = documentHighlights; @@ -56660,7 +57793,7 @@ var ts; var sourceFile = sourceFiles_4[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName) !== undefined) { + if (nameTable[internedName] !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -57200,7 +58333,7 @@ var ts; } // 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*/ {}); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ ts.createMap()); } }); return result; @@ -57228,7 +58361,7 @@ var ts; // 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)) { + if (symbol.name in previousIterationSymbolsCache) { return; } if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -57305,9 +58438,9 @@ var ts; // 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; }); + var result_5 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_5, /*previousIterationSymbolsCache*/ ts.createMap()); + return ts.forEach(result_5, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -57328,20 +58461,20 @@ var ts; 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); + var result_6 = []; + var symbol_2 = contextualType.getProperty(name); + if (symbol_2) { + result_6.push(symbol_2); } - if (contextualType.flags & 16384 /* Union */) { + if (contextualType.flags & 524288 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -57580,7 +58713,6 @@ var ts; case 172 /* PropertyAccessExpression */: case 139 /* QualifiedName */: case 9 /* StringLiteral */: - case 166 /* StringLiteralType */: case 84 /* FalseKeyword */: case 99 /* TrueKeyword */: case 93 /* NullKeyword */: @@ -57934,6 +59066,9 @@ var ts; * 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; } @@ -58016,7 +59151,7 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */ || tokenKind === 166 /* StringLiteralType */) { + else if (tokenKind === 9 /* StringLiteral */) { return token.parent.kind === 246 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { @@ -58135,12 +59270,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) { @@ -58440,9 +59575,9 @@ var ts; } } function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 /* StringLiteralType */ ? node.parent : node; + var searchNode = node.parent.kind === 166 /* LiteralType */ ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 256 /* StringLiteral */) { + if (type && type.flags & 32 /* StringLiteral */) { return type; } return undefined; @@ -58588,7 +59723,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = {}; + var nameTable = ts.createMap(); walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -58692,7 +59827,7 @@ var ts; 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 length_4 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -58701,8 +59836,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } - entries.push({ length: length_3, classification: convertClassification(type) }); - lastEnd = start + length_3; + entries.push({ length: length_4, classification: convertClassification(type) }); + lastEnd = start + length_4; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -58882,7 +60017,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9 /* StringLiteral */ || token === 166 /* StringLiteralType */) { + if (token === 9 /* StringLiteral */) { // Check to see if we finished up on a multiline string literal. var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { @@ -59021,7 +60156,6 @@ var ts; case 8 /* NumericLiteral */: return 4 /* numericLiteral */; case 9 /* StringLiteral */: - case 166 /* StringLiteralType */: return 6 /* stringLiteral */; case 10 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; @@ -59742,7 +60876,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; }); }; @@ -59753,7 +60887,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); }); }; } } @@ -59846,7 +60980,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. @@ -59899,6 +61033,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; @@ -59906,11 +61043,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; @@ -60296,6 +61433,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; @@ -60431,5 +61575,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.0"; /* tslint:enable:no-unused-variable */ diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index a14277d920b..50a2abcd887 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,8 +318,12 @@ declare namespace ts { JSDocTypedefTag = 279, JSDocPropertyTag = 280, JSDocTypeLiteral = 281, - SyntaxList = 282, - Count = 283, + JSDocLiteralType = 282, + JSDocNullKeyword = 283, + JSDocUndefinedKeyword = 284, + JSDocNeverKeyword = 285, + SyntaxList = 286, + Count = 287, FirstAssignment = 56, LastAssignment = 68, FirstReservedWord = 70, @@ -341,9 +348,9 @@ declare namespace ts { LastBinaryOperator = 68, FirstNode = 139, FirstJSDocNode = 257, - LastJSDocNode = 281, + LastJSDocNode = 282, FirstJSDocTagNode = 273, - LastJSDocTagNode = 281, + LastJSDocTagNode = 285, } enum NodeFlags { None = 0, @@ -607,8 +614,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; @@ -714,11 +722,17 @@ declare namespace ts { interface ObjectLiteralExpression extends PrimaryExpression, Declaration { properties: NodeArray; } + 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; @@ -1031,6 +1045,9 @@ 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; @@ -1109,6 +1126,11 @@ declare namespace ts { clauseEnd: number; antecedent: FlowNode; } + type FlowType = Type | IncompleteType; + interface IncompleteType { + flags: TypeFlags; + type: Type; + } interface AmdDependency { path: string; name: string; @@ -1305,6 +1327,7 @@ declare namespace ts { InElementType = 64, UseFullyQualifiedType = 128, InFirstTypeArgument = 256, + InTypeAlias = 512, } enum SymbolFormatFlags { None = 0, @@ -1363,18 +1386,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, @@ -1382,8 +1405,8 @@ declare namespace ts { MethodExcludes = 99263, GetAccessorExcludes = 41919, SetAccessorExcludes = 74687, - TypeParameterExcludes = 530912, - TypeAliasExcludes = 793056, + TypeParameterExcludes = 530920, + TypeAliasExcludes = 793064, AliasExcludes = 8388608, ModuleMember = 8914931, ExportHasLocal = 944, @@ -1403,49 +1426,63 @@ 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, + 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; } + interface EnumType extends Type { + memberTypes: Map; + } + interface EnumLiteralType extends LiteralType { + baseType: EnumType & UnionType; + } interface ObjectType extends Type { } interface InterfaceType extends ObjectType { @@ -1467,9 +1504,6 @@ declare namespace ts { } interface GenericType extends InterfaceType, TypeReference { } - interface TupleType extends ObjectType { - elementTypes: Type[]; - } interface UnionOrIntersectionType extends Type { types: Type[]; } @@ -1534,7 +1568,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 { @@ -1659,7 +1693,7 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; - wildcardDirectories?: Map; + wildcardDirectories?: MapLike; } enum WatchDirectoryFlags { None = 0, @@ -1667,7 +1701,7 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - wildcardDirectories: Map; + wildcardDirectories: MapLike; } interface ModuleResolutionHost { fileExists(fileName: string): boolean; @@ -1676,6 +1710,7 @@ declare namespace ts { directoryExists?(directoryName: string): boolean; realpath?(path: string): string; getCurrentDirectory?(): string; + getDirectories?(path: string): string[]; } interface ResolvedModule { resolvedFileName: string; @@ -1876,14 +1911,14 @@ declare namespace ts { 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 { @@ -1989,7 +2024,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; } @@ -2437,6 +2472,7 @@ declare namespace ts { const typeElement: string; /** enum E */ const enumElement: string; + const enumMemberElement: string; /** * Inside module and script only * const v = .. @@ -2549,7 +2585,7 @@ declare namespace ts { fileName?: string; reportDiagnostics?: boolean; moduleName?: string; - renamedDependencies?: Map; + renamedDependencies?: MapLike; } interface TranspileOutput { outputText: string; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 41d3676a415..6babaf9e4a0 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,10 +334,14 @@ 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"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 283] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 287] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; @@ -363,9 +367,9 @@ 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) { @@ -475,6 +479,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) { @@ -559,8 +564,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 +576,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 +587,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 +623,7 @@ var ts; NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var NodeCheckFlags = ts.NodeCheckFlags; (function (TypeFlags) { @@ -625,55 +631,63 @@ 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["FreshObjectLiteral"] = 16777216] = "FreshObjectLiteral"; /* @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"; /* @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) { @@ -893,7 +907,103 @@ var ts; })(ts.CharacterCodes || (ts.CharacterCodes = {})); var CharacterCodes = ts.CharacterCodes; })(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 +1022,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 +1062,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 +1106,36 @@ var ts; return undefined; } ts.forEach = forEach; - function contains(array, value, areEqual) { + /** 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; } } @@ -1024,20 +1176,48 @@ var ts; return count; } ts.countWhere = countWhere; + /** + * Filters an array by a predicate function. Returns the same array instance if the predicate is + * true for all elements, otherwise returns a new array instance containing the filtered subset. + */ 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_3 = array; _i < array_3.length; _i++) { + var item = array_3[_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++) { @@ -1074,11 +1254,15 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + loop: 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); + 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; @@ -1194,117 +1378,191 @@ 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; - function isEmpty(map) { - for (var id in map) { - if (hasProperty(map, id)) { - return false; - } - } - return true; - } - ts.isEmpty = isEmpty; - function clone(object) { - var result = {}; - for (var id in object) { - 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)) { - result[id] = second[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. + * Gets the owned, enumerable property keys of a map-like. * - * @param array the array of input elements. - * @param makeKey a function that produces a key for a given element. + * NOTE: This is intended for use with MapLike objects. For Map objects, use + * Object.keys instead as it offers better performance. * - * 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. + * @param map A map-like. */ - function arrayToMap(array, makeKey) { - var result = {}; - forEach(array, function (value) { - result[makeKey(value)] = value; - }); + 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.arrayToMap = arrayToMap; + 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; /** * 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; - if (map) { - for (var key in map) { - if (hasProperty(map, key)) { - result = callback(result, map[key], String(key)); - } - } + 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_8 = array; _i < array_8.length; _i++) { + var value = array_8[_i]; + result[makeKey(value)] = makeValue ? makeValue(value) : value; + } + return result; + } + ts.arrayToMap = arrayToMap; + function cloneMap(map) { + var clone = createMap(); + copyProperties(map, clone); + return clone; + } + ts.cloneMap = cloneMap; + function clone(object) { + var result = {}; + for (var id in object) { + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + 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; /** * Tests whether a value is an array. */ @@ -1329,9 +1587,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) { @@ -1786,10 +2042,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++) { @@ -1814,7 +2085,7 @@ var ts; if (hasRecursiveDirectoryWildcard) { continue spec; } - subpattern += "(/.+?)?"; + subpattern += doubleAsteriskRegexFragment; hasRecursiveDirectoryWildcard = true; hasWrittenComponent = true; } @@ -1826,6 +2097,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; } @@ -1846,8 +2130,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); @@ -1966,6 +2256,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) { @@ -2049,9 +2341,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"; } @@ -2275,14 +2571,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(); @@ -2291,23 +2587,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]; - } + (fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback); } function addFile(fileName, callback) { addFileWatcherCallback(fileName, callback); @@ -2319,8 +2610,9 @@ var ts; reduceDirWatcherRefCountForFile(watchedFile.fileName); } function removeFileWatcherCallback(filePath, callback) { - if (ts.hasProperty(fileWatcherCallbacks, filePath)) { - var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks[filePath]); + var callbacks = fileWatcherCallbacks[filePath]; + if (callbacks) { + var newCallbacks = ts.copyListRemovingItem(callback, callbacks); if (newCallbacks.length === 0) { delete fileWatcherCallbacks[filePath]; } @@ -2335,7 +2627,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); @@ -3056,6 +3348,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." }, @@ -3103,6 +3396,9 @@ 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." }, 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}'." }, @@ -3173,7 +3469,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}'." }, @@ -3201,6 +3497,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." }, @@ -3321,6 +3618,7 @@ var ts; 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." }, 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." }, @@ -3383,7 +3681,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 */, @@ -3507,7 +3805,7 @@ var ts; "|=": 67 /* BarEqualsToken */, "^=": 68 /* CaretEqualsToken */, "@": 55 /* AtToken */ - }; + }); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -3593,9 +3891,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; } @@ -5083,24 +5379,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; @@ -5118,7 +5396,7 @@ var ts; } ts.arrayIsEqualTo = arrayIsEqualTo; function hasResolvedModule(sourceFile, moduleNameText) { - return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + return !!(sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]); } ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { @@ -5127,14 +5405,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; } @@ -5156,7 +5434,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; @@ -5290,16 +5568,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); @@ -5994,6 +6276,7 @@ var ts; case 155 /* TypeReference */: return node.typeName; case 194 /* ExpressionWithTypeArguments */: + ts.Debug.assert(isEntityNameExpression(node.expression)); return node.expression; case 69 /* Identifier */: case 139 /* QualifiedName */: @@ -6459,7 +6742,7 @@ 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; @@ -6506,6 +6789,7 @@ var ts; case 146 /* MethodSignature */: case 225 /* ModuleDeclaration */: case 232 /* NamespaceImport */: + case 228 /* NamespaceExportDeclaration */: case 142 /* Parameter */: case 253 /* PropertyAssignment */: case 145 /* PropertyDeclaration */: @@ -6627,8 +6911,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 */ || @@ -6636,9 +6920,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; @@ -6890,7 +7178,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function createDiagnosticCollection() { var nonFileDiagnostics = []; - var fileDiagnostics = {}; + var fileDiagnostics = ts.createMap(); var diagnosticsModified = false; var modificationCount = 0; return { @@ -6904,12 +7192,12 @@ var ts; return modificationCount; } function reattachFileDiagnostics(newFile) { - if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) { - return; - } - for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) { - var diagnostic = _a[_i]; - diagnostic.file = newFile; + var diagnostics = fileDiagnostics[newFile.fileName]; + if (diagnostics) { + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + diagnostic.file = newFile; + } } } function add(diagnostic) { @@ -6943,9 +7231,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); } @@ -6956,9 +7242,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]); } } } @@ -6969,7 +7253,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", @@ -6982,7 +7266,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) @@ -7525,23 +7809,11 @@ var ts; isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - // Returns false if this heritage clause element's expression contains something unsupported - // (i.e. not a name or dotted name). - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 69 /* Identifier */) { - return true; - } - else if (isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } + 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); @@ -7570,6 +7842,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. @@ -7639,7 +7916,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 @@ -7934,7 +8211,6 @@ var ts; /// var ts; (function (ts) { - /* @internal */ ts.parseTime = 0; var NodeConstructor; var TokenConstructor; var IdentifierConstructor; @@ -8064,6 +8340,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); @@ -8342,14 +8620,17 @@ var ts; case 280 /* JSDocPropertyTag */: return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); + 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; @@ -8404,7 +8685,7 @@ var ts; var sourceFile; var parseDiagnostics; var syntaxCursor; - var token; + var currentToken; var sourceText; var nodeCount; var identifiers; @@ -8506,7 +8787,7 @@ var ts; syntaxCursor = _syntaxCursor; parseDiagnostics = []; parsingContext = 0; - identifiers = {}; + identifiers = ts.createMap(); identifierCount = 0; nodeCount = 0; contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 134217728 /* JavaScriptFile */ : 0 /* None */; @@ -8532,10 +8813,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; @@ -8729,34 +9010,43 @@ 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 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 @@ -8768,7 +9058,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; } @@ -8791,24 +9081,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(); } @@ -8824,14 +9114,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; @@ -8841,21 +9131,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(); } @@ -8902,7 +9192,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 @@ -8912,8 +9202,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(); @@ -8925,18 +9215,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(); @@ -8948,7 +9238,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]: @@ -8964,7 +9254,7 @@ var ts; return finishNode(node); } function parseContextualModifier(t) { - return token === t && tryParse(nextTokenCanFollowModifier); + return token() === t && tryParse(nextTokenCanFollowModifier); } function nextTokenIsOnSameLineAndCanFollowModifier() { nextToken(); @@ -8974,40 +9264,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) { @@ -9025,9 +9315,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 */: @@ -9035,19 +9325,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) { @@ -9062,23 +9352,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 */: @@ -9091,7 +9381,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: @@ -9111,11 +9401,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; @@ -9126,7 +9416,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; } @@ -9139,43 +9429,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() { @@ -9186,14 +9476,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. @@ -9534,7 +9824,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; @@ -9605,7 +9895,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, @@ -9633,7 +9923,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(); } @@ -9643,14 +9933,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); @@ -9683,7 +9970,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); @@ -9731,7 +10018,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 */); } } @@ -9742,7 +10029,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 /* AtToken */ || token === 97 /* ThisKeyword */; + return token() === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 55 /* AtToken */ || token() === 97 /* ThisKeyword */; } function setModifiers(node, modifiers) { if (modifiers) { @@ -9752,7 +10039,7 @@ var ts; } 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); @@ -9763,7 +10050,7 @@ var ts; // 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 && node.flags === 0 && ts.isModifierKind(token())) { // in cases like // 'use strict' // function foo(static) @@ -9858,7 +10145,7 @@ var ts; return finishNode(node); } function isIndexSignature() { - if (token !== 19 /* OpenBracketToken */) { + if (token() !== 19 /* OpenBracketToken */) { return false; } return lookAhead(isUnambiguouslyIndexSignature); @@ -9881,10 +10168,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; @@ -9900,18 +10187,18 @@ 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); @@ -9925,7 +10212,7 @@ 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.name = name; @@ -9942,7 +10229,7 @@ var ts; 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. @@ -9955,39 +10242,39 @@ var ts; 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 */ || 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(); @@ -9999,7 +10286,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 */); @@ -10039,10 +10326,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 */: @@ -10054,13 +10350,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 { @@ -10080,7 +10381,7 @@ var ts; } } function isStartOfType() { - switch (token) { + switch (token()) { case 117 /* AnyKeyword */: case 132 /* StringKeyword */: case 130 /* NumberKeyword */: @@ -10097,7 +10398,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. @@ -10108,7 +10414,7 @@ var ts; } function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + return token() === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); } function parseArrayTypeOrHigher() { var type = parseNonArrayType(); @@ -10122,7 +10428,7 @@ var ts; } function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { var type = parseConstituentType(); - if (token === operator) { + if (token() === operator) { var types = [type]; types.pos = type.pos; while (parseOptional(operator)) { @@ -10142,21 +10448,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(); @@ -10166,7 +10472,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token === 18 /* CloseParenToken */ || token === 22 /* DotDotDotToken */) { + if (token() === 18 /* CloseParenToken */ || token() === 22 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -10174,17 +10480,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; } @@ -10207,7 +10513,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + if (token() === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -10221,7 +10527,7 @@ var ts; if (isStartOfFunctionType()) { return parseFunctionOrConstructorType(156 /* FunctionType */); } - if (token === 92 /* NewKeyword */) { + if (token() === 92 /* NewKeyword */) { return parseFunctionOrConstructorType(157 /* ConstructorType */); } return parseUnionTypeOrHigher(); @@ -10231,7 +10537,7 @@ var ts; } // EXPRESSIONS function isStartOfLeftHandSideExpression() { - switch (token) { + switch (token()) { case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: case 93 /* NullKeyword */: @@ -10259,7 +10565,7 @@ var ts; if (isStartOfLeftHandSideExpression()) { return true; } - switch (token) { + switch (token()) { case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: @@ -10289,10 +10595,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() { @@ -10315,7 +10621,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. @@ -10324,7 +10630,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; @@ -10346,7 +10652,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(); } @@ -10378,7 +10684,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'. @@ -10394,7 +10700,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()) { @@ -10430,7 +10736,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); @@ -10442,7 +10748,7 @@ 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); @@ -10481,7 +10787,7 @@ var ts; var isAsync = !!(arrowFunction.flags & 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) @@ -10493,10 +10799,10 @@ var ts; // 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. @@ -10506,16 +10812,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 */) { @@ -10604,7 +10910,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(); @@ -10618,16 +10924,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 */; } } @@ -10657,19 +10963,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) @@ -10742,16 +11048,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) @@ -10772,13 +11078,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 */: @@ -10835,7 +11141,7 @@ var ts; } function parsePrefixUnaryExpression() { var node = createNode(185 /* PrefixUnaryExpression */); - node.operator = token; + node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); @@ -10859,7 +11165,7 @@ var ts; return finishNode(node); } function isAwaitExpression() { - if (token === 119 /* AwaitKeyword */) { + if (token() === 119 /* AwaitKeyword */) { if (inAwaitContext()) { return true; } @@ -10875,25 +11181,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); @@ -10907,8 +11230,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] @@ -10916,9 +11239,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 */: @@ -10935,6 +11259,10 @@ var ts; // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); + case 119 /* AwaitKeyword */: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } default: return parseIncrementExpression(); } @@ -10942,17 +11270,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 */: @@ -10960,6 +11288,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 @@ -10984,23 +11313,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); } @@ -11037,7 +11366,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 @@ -11097,7 +11426,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 '.'. @@ -11149,7 +11478,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); @@ -11166,11 +11495,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 */: @@ -11178,7 +11507,7 @@ 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 = []; @@ -11186,12 +11515,12 @@ var ts; 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)); @@ -11209,7 +11538,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 @@ -11238,7 +11567,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); @@ -11251,7 +11580,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) { @@ -11264,14 +11593,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) { + switch (token()) { case 9 /* StringLiteral */: node.initializer = parseLiteralNode(); break; @@ -11321,7 +11650,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; @@ -11334,7 +11663,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; @@ -11345,10 +11674,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); @@ -11360,7 +11689,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 @@ -11376,7 +11705,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(); @@ -11408,7 +11737,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. @@ -11444,7 +11773,7 @@ var ts; } } function parsePrimaryExpression() { - switch (token) { + switch (token()) { case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 11 /* NoSubstitutionTemplateLiteral */: @@ -11500,8 +11829,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() { @@ -11539,7 +11868,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 @@ -11547,7 +11876,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; @@ -11615,7 +11944,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); @@ -11695,8 +12024,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 { @@ -11722,11 +12051,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 */); @@ -11778,7 +12107,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 */); @@ -11812,10 +12141,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); } @@ -11858,19 +12187,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 */: @@ -11920,16 +12249,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; @@ -11945,7 +12274,7 @@ var ts; return lookAhead(isDeclaration); } function isStartOfStatement() { - switch (token) { + switch (token()) { case 55 /* AtToken */: case 23 /* SemicolonToken */: case 15 /* OpenBraceToken */: @@ -11998,7 +12327,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 { @@ -12006,7 +12335,7 @@ var ts; return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } function parseStatement() { - switch (token) { + switch (token()) { case 23 /* SemicolonToken */: return parseEmptyStatement(); case 15 /* OpenBraceToken */: @@ -12079,7 +12408,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 */: @@ -12102,7 +12431,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); @@ -12125,10 +12454,10 @@ var ts; } 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; } @@ -12136,7 +12465,7 @@ var ts; } // DECLARATIONS function parseArrayBindingElement() { - if (token === 24 /* CommaToken */) { + if (token() === 24 /* CommaToken */) { return createNode(193 /* OmittedExpression */); } var node = createNode(169 /* BindingElement */); @@ -12149,7 +12478,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 { @@ -12175,13 +12504,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(); @@ -12190,14 +12519,14 @@ 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 */: @@ -12219,7 +12548,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 { @@ -12304,7 +12633,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 { @@ -12337,12 +12666,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: @@ -12354,17 +12683,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... @@ -12375,7 +12704,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 @@ -12425,8 +12754,8 @@ var ts; 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)) { @@ -12454,9 +12783,9 @@ var ts; 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; @@ -12468,7 +12797,7 @@ var ts; return modifiers; } function parseClassElement() { - if (token === 23 /* SemicolonToken */) { + if (token() === 23 /* SemicolonToken */) { var result = createNode(198 /* SemicolonClassElement */); nextToken(); return finishNode(result); @@ -12480,7 +12809,7 @@ var ts; if (accessor) { return accessor; } - if (token === 121 /* ConstructorKeyword */) { + if (token() === 121 /* ConstructorKeyword */) { return parseConstructorDeclaration(fullStart, decorators, modifiers); } if (isIndexSignature()) { @@ -12488,11 +12817,11 @@ 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) { @@ -12542,7 +12871,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 @@ -12553,9 +12882,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); @@ -12565,13 +12894,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); @@ -12653,7 +12982,7 @@ var ts; var node = createNode(225 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - if (token === 137 /* GlobalKeyword */) { + if (token() === 137 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 131072 /* GlobalAugmentation */; @@ -12661,7 +12990,7 @@ var ts; else { node.name = parseLiteralNode(/*internName*/ true); } - if (token === 15 /* OpenBraceToken */) { + if (token() === 15 /* OpenBraceToken */) { node.body = parseModuleBlock(); } else { @@ -12671,7 +13000,7 @@ var ts; } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (token === 137 /* GlobalKeyword */) { + if (token() === 137 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); } @@ -12680,14 +13009,14 @@ var ts; } 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() { @@ -12712,7 +13041,7 @@ 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; @@ -12734,8 +13063,8 @@ var ts; // 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 */); } @@ -12760,7 +13089,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); } @@ -12778,7 +13107,7 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - if (token === 9 /* StringLiteral */) { + if (token() === 9 /* StringLiteral */) { var result = parseLiteralNode(); internIdentifier(result.text); return result; @@ -12825,14 +13154,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(); @@ -12859,7 +13188,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(); } @@ -12997,7 +13326,7 @@ var ts; var JSDocParser; (function (JSDocParser) { function isJSDocType() { - switch (token) { + switch (token()) { case 37 /* AsteriskToken */: case 53 /* QuestionToken */: case 17 /* OpenParenToken */: @@ -13010,13 +13339,13 @@ 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 */); scanner.setText(content, start, length); - token = scanner.scan(); + currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); var diagnostics = parseDiagnostics; clearState(); @@ -13036,12 +13365,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; @@ -13052,20 +13381,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(); @@ -13078,7 +13407,7 @@ var ts; return type; } function parseBasicTypeExpression() { - switch (token) { + switch (token()) { case 37 /* AsteriskToken */: return parseJSDocAllType(); case 53 /* QuestionToken */: @@ -13105,9 +13434,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() { @@ -13137,7 +13473,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(); } @@ -13154,12 +13490,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; } @@ -13203,7 +13539,7 @@ var ts; function parseJSDocRecordMember() { var result = createNode(266 /* JSDocRecordMember */); result.name = parseSimplePropertyName(); - if (token === 54 /* ColonToken */) { + if (token() === 54 /* ColonToken */) { nextToken(); result.type = parseJSDocType(); } @@ -13252,6 +13588,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 ? @@ -13265,12 +13606,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); } @@ -13290,14 +13631,14 @@ var ts; } 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; @@ -13325,8 +13666,8 @@ var ts; var canParseTag = true; var seenAsterisk = true; nextJSDocToken(); - while (token !== 1 /* EndOfFileToken */) { - switch (token) { + while (token() !== 1 /* EndOfFileToken */) { + switch (token()) { case 55 /* AtToken */: if (canParseTag) { parseTag(); @@ -13371,12 +13712,12 @@ var ts; 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 */); + ts.Debug.assert(token() === 55 /* AtToken */); var atToken = createNode(55 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); @@ -13422,7 +13763,7 @@ var ts; } } function tryParseTypeExpression() { - if (token !== 15 /* OpenBraceToken */) { + if (token() !== 15 /* OpenBraceToken */) { return undefined; } var typeExpression = parseJSDocTypeExpression(); @@ -13443,7 +13784,7 @@ var ts; } parseExpected(20 /* CloseBracketToken */); } - else if (ts.tokenIsIdentifierOrKeyword(token)) { + else if (ts.tokenIsIdentifierOrKeyword(token())) { name = parseJSDocIdentifierName(); } if (!name) { @@ -13536,9 +13877,9 @@ 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); @@ -13570,7 +13911,7 @@ 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(); @@ -13614,7 +13955,7 @@ var ts; typeParameter.name = name_9; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token === 24 /* CommaToken */) { + if (token() === 24 /* CommaToken */) { nextJSDocToken(); } else { @@ -13630,10 +13971,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) { @@ -13760,8 +14101,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } } @@ -13898,8 +14239,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; visitNode(node); } return; @@ -14132,7 +14473,6 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.bindTime = 0; (function (ModuleInstanceState) { ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; @@ -14204,9 +14544,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() { @@ -14244,7 +14585,7 @@ var ts; options = opts; languageVersion = ts.getEmitScriptTarget(options); inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; + classifiableNames = ts.createMap(); symbolCount = 0; Symbol = ts.objectAllocator.getSymbolConstructor(); if (!file.locals) { @@ -14283,10 +14624,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; @@ -14388,7 +14729,10 @@ var ts; // 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 @@ -14400,6 +14744,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. @@ -14407,36 +14756,38 @@ 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 (declaration.flags & 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; @@ -14469,8 +14820,8 @@ var ts; // 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 */)) { 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; @@ -14510,7 +14861,7 @@ var ts; if (containerFlags & 1 /* IsContainer */) { container = blockScopeContainer = node; if (containerFlags & 32 /* HasLocals */) { - container.locals = {}; + container.locals = ts.createMap(); } addToContainerChain(container); } @@ -14692,15 +15043,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 */: @@ -14709,9 +15054,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 */: @@ -14733,10 +15077,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 */, @@ -14781,7 +15121,7 @@ var ts; }; } function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingSwitchStatement(switchStatement)) { + if (!isNarrowingExpression(switchStatement.expression)) { return antecedent; } setFlowNodeReferenced(antecedent); @@ -15419,8 +15759,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; @@ -15429,7 +15769,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 */) { @@ -15477,7 +15817,7 @@ var ts; // fall through. default: if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; + blockScopeContainer.locals = ts.createMap(); addToContainerChain(blockScopeContainer); } declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); @@ -15738,7 +16078,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 */: @@ -15754,7 +16094,7 @@ 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 */; return; @@ -15802,10 +16142,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 */: @@ -15856,18 +16196,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) { @@ -15889,7 +16226,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) { @@ -15925,20 +16262,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. @@ -15957,7 +16299,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 */); @@ -16000,7 +16342,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; } @@ -16167,7 +16509,6 @@ var ts; return node.id; } ts.getNodeId = getNodeId; - ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { symbol.id = nextSymbolId; @@ -16193,7 +16534,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); @@ -16249,32 +16590,39 @@ var ts; 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 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 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. @@ -16318,10 +16666,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 = []; @@ -16362,26 +16708,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 */, @@ -16389,8 +16754,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 */, @@ -16398,17 +16763,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", @@ -16418,10 +16783,10 @@ 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(); // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. var _displayBuilder; var TypeSystemPropertyName; @@ -16431,10 +16796,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) { @@ -16462,13 +16825,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 */) @@ -16482,9 +16845,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; @@ -16505,9 +16868,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; } @@ -16529,12 +16892,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); @@ -16550,28 +16913,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]); } } } @@ -16599,7 +16951,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); @@ -16612,14 +16964,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) { @@ -16634,24 +16984,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. @@ -16760,7 +17112,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 */ || @@ -16814,7 +17166,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; @@ -16850,7 +17202,7 @@ var ts; case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: case 222 /* InterfaceDeclaration */: - if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { if (lastLocation && lastLocation.flags & 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 @@ -16880,7 +17232,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; } @@ -16945,8 +17297,9 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation)) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -16989,7 +17342,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); @@ -17021,34 +17374,35 @@ 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 false; + 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 checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0); // 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)); } } @@ -17127,7 +17481,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); @@ -17143,9 +17497,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); } } } @@ -17177,6 +17531,10 @@ var ts; // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable); var symbolFromModule = getExportOfModule(targetSymbol, name_10.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_10.text === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; @@ -17196,10 +17554,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) { @@ -17220,7 +17578,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."); @@ -17228,6 +17586,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; @@ -17260,6 +17619,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); @@ -17287,13 +17647,13 @@ 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) { @@ -17306,7 +17666,7 @@ var ts; } var symbol; if (name.kind === 69 /* Identifier */) { - var message = meaning === 1536 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; @@ -17315,7 +17675,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); if (!namespace || ts.nodeIsMissing(right)) { return undefined; } @@ -17379,7 +17739,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(moduleReferenceLiteral, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); + } + else { + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + } } return undefined; } @@ -17418,7 +17785,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] = { @@ -17426,7 +17793,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]; } @@ -17446,12 +17813,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); @@ -17461,7 +17828,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++) { @@ -17516,8 +17883,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) { @@ -17525,6 +17892,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; @@ -17543,14 +17916,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); } } } @@ -17568,7 +17939,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; @@ -17595,7 +17966,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) { @@ -17618,11 +17989,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 */)) { @@ -17653,12 +18024,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; @@ -17705,7 +18076,7 @@ var ts; 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; @@ -17799,11 +18170,11 @@ 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); @@ -17855,6 +18226,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"; @@ -18004,38 +18400,48 @@ var ts; 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) { + 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 */) { + else if (type.flags & 32 /* StringLiteral */) { writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } + else if (type.flags & 64 /* NumberLiteral */) { + writer.writeStringLiteral(type.text); + } else { // Should never get here // { ... } @@ -18061,7 +18467,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 */); @@ -18083,6 +18489,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 @@ -18110,16 +18521,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 */); } @@ -18139,7 +18550,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 @@ -18562,13 +18973,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) { @@ -18586,7 +18997,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); } @@ -18639,7 +19050,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 */) { @@ -18688,7 +19099,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. @@ -18765,7 +19176,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); @@ -18780,7 +19191,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 && 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; @@ -18817,7 +19228,7 @@ 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) { @@ -18865,9 +19276,14 @@ 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); } @@ -18882,7 +19298,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; @@ -18890,23 +19306,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 checkExpressionCached(element.initializer); } 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; @@ -18918,7 +19332,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; }); @@ -18927,24 +19341,24 @@ 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) { 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 e.kind === 193 /* OmittedExpression */ ? 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 @@ -18953,10 +19367,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 @@ -19019,7 +19433,7 @@ var ts; if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var type = undefined; + var type = void 0; // Handle certain special assignment kinds, which happen to union across multiple declarations: // * module.exports = expr // * exports.p = expr @@ -19027,11 +19441,19 @@ var ts; // * className.prototype.method = expr if (declaration.kind === 187 /* BinaryExpression */ || declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) { - type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ? + // Use JS Doc type if present on parent expression statement + if (declaration.flags & 134217728 /* 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); })); + checkExpressionCached(decl.parent.right); }); + type = getUnionType(declaredTypes, /*subtypeReduction*/ true); } - if (type === undefined) { + else { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } if (!popTypeResolution()) { @@ -19128,9 +19550,9 @@ var ts; 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; @@ -19186,7 +19608,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); @@ -19257,7 +19679,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); @@ -19289,7 +19711,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); @@ -19307,25 +19729,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); @@ -19352,7 +19777,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; } @@ -19387,7 +19812,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]; @@ -19422,8 +19847,8 @@ var ts; 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; } @@ -19437,7 +19862,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); @@ -19446,16 +19871,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; } @@ -19470,8 +19895,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); @@ -19482,14 +19908,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; } } @@ -19501,19 +19927,80 @@ 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 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] = createType(256 /* EnumLiteral */); + memberType.symbol = memberSymbol; + memberType.baseType = enumType; + memberType.text = "" + 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; @@ -19537,11 +20024,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); @@ -19574,7 +20064,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); @@ -19625,7 +20115,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; @@ -19635,7 +20125,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); @@ -19645,7 +20135,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; } } @@ -19662,19 +20152,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); @@ -19684,7 +20182,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); @@ -19710,7 +20208,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; @@ -19720,17 +20218,17 @@ 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); @@ -19748,23 +20246,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]; @@ -19819,7 +20300,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 @@ -19845,7 +20326,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 @@ -19910,7 +20391,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)); } @@ -19928,22 +20409,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); } } @@ -19951,7 +20429,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; @@ -19959,13 +20437,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; } } } @@ -19978,7 +20454,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; } } @@ -19986,7 +20462,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 @@ -19995,7 +20471,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); @@ -20008,19 +20484,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; @@ -20029,7 +20505,7 @@ 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]; @@ -20048,7 +20524,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; } @@ -20062,11 +20538,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 */ | @@ -20074,50 +20559,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; } @@ -20131,7 +20620,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; } @@ -20160,7 +20649,7 @@ var ts; } } if (propTypes.length) { - return getUnionType(propTypes); + return getUnionType(propTypes, /*subtypeReduction*/ true); } } return undefined; @@ -20245,7 +20734,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; @@ -20268,8 +20757,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) { @@ -20297,6 +20786,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; @@ -20307,7 +20799,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; } @@ -20397,7 +20889,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); @@ -20421,7 +20913,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]; } } @@ -20445,7 +20937,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; @@ -20489,7 +20981,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; } @@ -20521,24 +21013,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 @@ -20552,20 +21047,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)); @@ -20625,8 +21129,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; @@ -20635,7 +21140,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) { @@ -20664,15 +21169,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) : @@ -20713,7 +21218,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; } @@ -20727,7 +21232,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); @@ -20741,8 +21246,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); } /** @@ -20776,16 +21281,46 @@ 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) { @@ -20793,32 +21328,70 @@ var ts; } 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) { + if (type.flags & 524288 /* Union */) { + addTypesToUnion(typeSet, type.types); + } + else if (type.flags & 1 /* Any */) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && type.flags & 6144 /* Nullable */) { + if (type.flags & 2048 /* Undefined */) typeSet.containsUndefined = true; - if (type.flags & 64 /* Null */) + if (type.flags & 4096 /* Null */) typeSet.containsNull = true; - if (!(type.flags & 2097152 /* ContainsWideningType */)) + if (!(type.flags & 33554432 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } - else if (type !== neverType && !ts.contains(typeSet, type)) { - typeSet.push(type); + else if (!(type.flags & 8192 /* Never */)) { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(type.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])) { @@ -20836,14 +21409,14 @@ var ts; } } } - // 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) { + // 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; } @@ -20851,17 +21424,11 @@ 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); } if (typeSet.length === 0) { @@ -20869,84 +21436,112 @@ var ts; 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, getTypeFromTypeNode), /*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, getTypeFromTypeNode), 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 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 = checkExpression(node.literal); } return links.resolvedType; } @@ -20985,7 +21580,7 @@ var ts; } return links.resolvedType; } - function getTypeFromTypeNode(node) { + function getTypeFromTypeNode(node, aliasSymbol, aliasTypeArguments) { switch (node.kind) { case 117 /* AnyKeyword */: case 258 /* JSDocAllType */: @@ -21007,11 +21602,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); @@ -21028,9 +21631,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 */: @@ -21044,7 +21647,7 @@ var ts; 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 */: @@ -21092,6 +21695,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) { @@ -21124,7 +21728,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; @@ -21162,7 +21766,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; @@ -21199,9 +21803,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; } @@ -21256,10 +21862,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 @@ -21268,20 +21874,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; @@ -21326,10 +21929,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; @@ -21341,26 +21944,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); @@ -21486,8 +22095,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; @@ -21516,6 +22125,73 @@ var ts; sourceNonRestParamCount; } } + function isEnumTypeRelatedTo(source, target, errorReporter) { + if (source === target) { + return true; + } + if (source.symbol.name !== target.symbol.name || !(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */)) { + return 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 false; + } + } + } + return 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 */ | 64 /* NumberLiteral */) && target.flags & 16 /* Enum */) + return true; + if (source.flags & 64 /* NumberLiteral */ && target.flags & 256 /* EnumLiteral */ && source.text === target.text) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + 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. @@ -21564,6 +22240,16 @@ 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 @@ -21576,37 +22262,9 @@ var ts; 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 & 16777216 /* FreshObjectLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -21617,24 +22275,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; @@ -21644,7 +22302,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 @@ -21662,13 +22320,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; @@ -21683,7 +22341,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; @@ -21695,9 +22353,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; @@ -21705,14 +22363,17 @@ var ts; } } if (reportErrors) { + if (source.flags & 2588672 /* ObjectType */ && target.flags & 8190 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } 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; @@ -21720,8 +22381,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; @@ -21735,7 +22396,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 || @@ -21744,7 +22405,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)) { @@ -21762,7 +22423,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)) { @@ -21795,18 +22456,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) { @@ -21830,18 +22483,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) { @@ -21921,7 +22566,7 @@ var ts; } sourceStack[depth] = source; targetStack[depth] = target; - maybeStack[depth] = {}; + maybeStack[depth] = ts.createMap(); maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; @@ -21954,7 +22599,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 @@ -21969,7 +22614,7 @@ var ts; } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288 /* ObjectLiteral */); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 8388608 /* ObjectLiteral */); for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); @@ -22042,7 +22687,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); @@ -22163,7 +22808,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 */; } @@ -22201,27 +22846,6 @@ 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; @@ -22248,7 +22872,7 @@ 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); @@ -22266,12 +22890,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; @@ -22321,8 +22945,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; @@ -22383,31 +23009,23 @@ 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; - } - return flags; - } function getCommonSupertype(types) { if (!strictNullChecks) { return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); } - 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 */); + 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 @@ -22443,50 +23061,81 @@ 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 isUnitUnionType(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 getBaseTypeOfUnitType(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, getBaseTypeOfUnitType)) : + 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_8 = types; _i < types_8.length; _i++) { + var t = types_8[_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 === emptyStringType ? 32 /* StringLiteral */ : 0 : + type.flags & 64 /* NumberLiteral */ ? type === zeroType ? 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; @@ -22512,7 +23161,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); @@ -22528,7 +23177,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 & 16777216 /* FreshObjectLiteral */)) { return type; } var regularType = type.regularType; @@ -22538,7 +23187,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 /* FreshObjectLiteral */; type.regularType = regularNew; return regularNew; } @@ -22552,24 +23201,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; @@ -22587,7 +23233,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)) { @@ -22595,22 +23241,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))); } @@ -22655,7 +23298,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); @@ -22698,12 +23341,27 @@ var ts; isFixed: false }; } + // 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 inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; - var visited = {}; + var visited = ts.createMap(); inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -22714,16 +23372,27 @@ 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 + 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 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. var matchingTypes = void 0; - for (var _i = 0, _a = target.types; _i < _a.length; _i++) { - var t = _a[_i]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var t = _c[_b]; if (typeIdenticalToSomeType(t, source.types)) { (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); @@ -22737,14 +23406,14 @@ 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; @@ -22769,7 +23438,7 @@ var ts; } } } - 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; @@ -22778,22 +23447,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(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; } @@ -22810,21 +23471,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; } @@ -22832,7 +23489,7 @@ var ts; return; } var key = source.id + "," + target.id; - if (ts.hasProperty(visited, key)) { + if (visited[key]) { return; } visited[key] = true; @@ -22901,8 +23558,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_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -22921,7 +23578,7 @@ 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]; @@ -22934,7 +23591,7 @@ var ts; var inferences = getInferenceCandidates(context, index); if (inferences.length) { // 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(inferences, /*subtypeReduction*/ true) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -23016,10 +23673,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 */: @@ -23031,16 +23684,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; } @@ -23053,6 +23707,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 && + isUnitUnionType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -23079,7 +23775,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++) { @@ -23094,70 +23790,81 @@ 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) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (reducedType !== neverType) { + return reducedType; } } return declaredType; } + function getTypeFactsOfTypes(types) { + var result = 0 /* None */; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_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 === emptyStringType ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : + type === emptyStringType ? 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 === zeroType || type.flags & 256 /* EnumLiteral */ && 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) { @@ -23254,26 +23961,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 = checkExpression(clause.expression); + return isUnitType(caseType) ? caseType : undefined; } - return undefined; + return neverType; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); @@ -23281,26 +23993,56 @@ 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) { return declaredType; @@ -23344,7 +24086,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; } @@ -23369,19 +24111,9 @@ 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)) : + return declaredType.flags & 524288 /* Union */ ? + getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this @@ -23395,32 +24127,43 @@ var ts; return undefined; } function getTypeAtFlowCondition(flow) { - var type = getTypeAtFlowNode(flow.antecedent); + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); if (type !== neverType) { // 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 + // 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 reverting to the declared type and then // narrow that. var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; type = narrowType(type, flow.expression, assumeTrue); - if (type === neverType) { + if (type === neverType && isIncomplete(flowType)) { type = narrowType(declaredType, flow.expression, assumeTrue); } } - 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 @@ -23431,14 +24174,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); } @@ -23446,25 +24198,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. @@ -23474,6 +24232,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. @@ -23481,10 +24245,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) { @@ -23494,26 +24285,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 */: @@ -23523,25 +24317,35 @@ 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 (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 !== neverType ? narrowedType : type; + } + return isUnitType(valueType) ? filterType(type, function (t) { return t !== valueType; }) : 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. @@ -23553,72 +24357,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 === neverType ? 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, t)); }); + return caseType === neverType ? 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. @@ -23627,10 +24397,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)) { @@ -23645,13 +24411,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) { @@ -23665,28 +24435,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 !== neverType) { + 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, targetType) ? 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); @@ -23694,6 +24465,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) { @@ -23775,20 +24550,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); @@ -23834,16 +24638,36 @@ var ts; 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); + // 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 || + flowContainer !== declarationContainer || 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; @@ -24051,10 +24875,6 @@ var ts; return getInferredClassType(classSymbol); } } - var type = getContextuallyTypedThisType(container); - if (type) { - return type; - } var thisType = getThisTypeOfDeclaration(container); if (thisType) { return thisType; @@ -24063,7 +24883,7 @@ 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); + return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*flowContainer*/ undefined); } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); @@ -24272,11 +25092,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; @@ -24343,7 +25163,7 @@ 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; @@ -24431,6 +25251,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); @@ -24456,14 +25280,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_11 = types; _i < types_11.length; _i++) { + var current = types_11[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -24481,7 +25305,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; }); } @@ -24490,7 +25314,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 @@ -24628,6 +25452,30 @@ var ts; } return undefined; } + function isLiteralTypeLocation(node) { + var parent = node.parent; + switch (parent.kind) { + case 187 /* BinaryExpression */: + switch (parent.operatorToken.kind) { + case 32 /* EqualsEqualsEqualsToken */: + case 33 /* ExclamationEqualsEqualsToken */: + case 30 /* EqualsEqualsToken */: + case 31 /* ExclamationEqualsToken */: + return true; + } + break; + case 188 /* ConditionalExpression */: + return (node === parent.whenTrue || + node === parent.whenFalse) && + isLiteralTypeLocation(parent); + case 178 /* ParenthesizedExpression */: + return isLiteralTypeLocation(parent); + case 249 /* CaseClause */: + case 166 /* LiteralType */: + return true; + } + return false; + } // If the given type is an object or union type, if that type has a single signature, and if // that signature is non-generic, return the signature. Otherwise return undefined. function getNonGenericSignature(type) { @@ -24664,13 +25512,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_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -24766,7 +25614,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; } @@ -24780,7 +25628,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 */) { @@ -24795,7 +25643,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); @@ -24803,7 +25653,7 @@ 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); @@ -24838,7 +25688,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 { @@ -24854,14 +25704,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 && @@ -24901,7 +25751,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); @@ -24948,7 +25798,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); } @@ -24960,8 +25810,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 /* FreshObjectLiteral */; + result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -25028,10 +25878,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 @@ -25122,7 +25971,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; @@ -25138,7 +25987,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 @@ -25147,9 +25996,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 @@ -25180,17 +26029,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) { @@ -25254,7 +26103,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; @@ -25352,7 +26201,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 @@ -25375,7 +26224,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)); } } @@ -25468,12 +26317,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; } @@ -25482,9 +26331,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); @@ -25505,14 +26354,14 @@ var ts; 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)); + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 268435456 /* ThisType */ ? apparentType : type)); } return unknownType; } @@ -25531,15 +26380,18 @@ var ts; checkClassPropertyAccess(node, left, apparentType, prop); } var propType = getTypeOfSymbol(prop); + if (prop.flags & 8 /* EnumMember */ && isLiteralContextForType(node, propType)) { + propType = getDeclaredTypeOfSymbol(prop); + } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // 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 isValidPropertyAccess(node, propertyName) { var left = node.kind === 172 /* PropertyAccessExpression */ @@ -25652,9 +26504,10 @@ var ts; } } // 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; @@ -25718,7 +26571,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)); } @@ -25797,7 +26650,7 @@ var ts; 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 @@ -25890,7 +26743,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) { @@ -26024,9 +26877,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; @@ -26211,10 +27062,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 { @@ -26573,8 +27424,8 @@ var ts; // 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))) { + (isTypeAny(apparentType) && funcType.flags & 16384 /* TypeParameter */) || + (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 524288 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { // 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) { @@ -26673,8 +27524,20 @@ var ts; } 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)) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + if (baseTypes.length) { + var baseType = baseTypes[0]; + if (flags & 16 /* Protected */ && + baseType.symbol === declaration.parent.symbol) { + return true; + } + } + } if (flags & 8 /* Private */) { error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); } @@ -26693,7 +27556,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 524288 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -26730,7 +27593,7 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 524288 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); @@ -26853,7 +27716,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; @@ -26865,6 +27728,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); @@ -27004,7 +27873,7 @@ var ts; } // 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); + type = contextualSignature ? getUnionType(types, /*subtypeReduction*/ true) : getCommonSupertype(types); if (!type) { if (funcIsGenerator) { error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); @@ -27013,7 +27882,7 @@ var ts; 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 isAsync ? createPromiseReturnType(func, getUnionType(types, /*subtypeReduction*/ true)) : getUnionType(types, /*subtypeReduction*/ true); } } if (funcIsGenerator) { @@ -27047,24 +27916,18 @@ 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 (!isUnitUnionType(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 */)) { @@ -27128,7 +27991,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. @@ -27257,7 +28120,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132 /* NumberLike */)) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 340 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -27369,16 +28232,22 @@ var ts; } function checkPrefixUnaryExpression(node) { var operandType = checkExpression(node.operand); + if (node.operator === 36 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */ && isLiteralContextForType(node, numberType)) { + return 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); @@ -27405,10 +28274,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_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -27423,20 +28292,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_14 = types; _i < types_14.length; _i++) { + var t = types_14[_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_15 = types; _a < types_15.length; _a++) { + var t = types_15[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -27445,7 +28314,7 @@ 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; @@ -27456,7 +28325,7 @@ var ts; // 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 @@ -27470,10 +28339,10 @@ var ts; // 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; @@ -27544,8 +28413,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); @@ -27577,7 +28449,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); @@ -27607,7 +28479,14 @@ var ts; return sourceType; } 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); @@ -27648,17 +28527,17 @@ var ts; // 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)); } @@ -27677,20 +28556,20 @@ var ts; // 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; } @@ -27726,6 +28605,12 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: + var leftIsUnit = isUnitUnionType(leftType); + var rightIsUnit = isUnitUnionType(rightType); + if (!leftIsUnit || !rightIsUnit) { + leftType = leftIsUnit ? getBaseTypeOfUnitType(leftType) : leftType; + rightType = rightIsUnit ? getBaseTypeOfUnitType(rightType) : rightType; + } if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { reportOperatorError(); } @@ -27735,9 +28620,13 @@ 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 : getBaseTypeOfUnitType(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); @@ -27746,8 +28635,8 @@ var ts; } // 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)); @@ -27847,14 +28736,66 @@ 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 typeContainsLiteralFromEnum(type, enumType) { + if (type.flags & 524288 /* Union */) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 256 /* EnumLiteral */ && t.baseType === enumType) { + return true; + } + } + } + if (type.flags & 256 /* EnumLiteral */) { + return type.baseType === enumType; + } + return false; + } + function isLiteralContextForType(node, type) { + if (isLiteralTypeLocation(node)) { + return true; + } + var contextualType = getContextualType(node); + 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 (type === apparentType) { + return true; + } + contextualType = apparentType; + } + if (type.flags & 2 /* String */) { + return maybeTypeOfKind(contextualType, 32 /* StringLiteral */); + } + if (type.flags & 4 /* Number */) { + return maybeTypeOfKind(contextualType, (64 /* NumberLiteral */ | 256 /* EnumLiteral */)); + } + if (type.flags & 8 /* Boolean */) { + return maybeTypeOfKind(contextualType, 128 /* BooleanLiteral */) && !isTypeAssignableTo(booleanType, contextualType); + } + if (type.flags & 16 /* Enum */) { + return typeContainsLiteralFromEnum(contextualType, type); + } + } + return false; + } + function checkLiteralExpression(node) { + if (node.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9 /* StringLiteral */: + return isLiteralContextForType(node, stringType) ? getLiteralTypeForText(32 /* StringLiteral */, node.text) : stringType; + case 8 /* NumericLiteral */: + return isLiteralContextForType(node, numberType) ? getLiteralTypeForText(64 /* NumberLiteral */, node.text) : numberType; + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + return isLiteralContextForType(node, booleanType) ? node.kind === 99 /* TrueKeyword */ ? trueType : falseType : booleanType; } - return stringType; } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with @@ -27953,11 +28894,6 @@ var ts; } return type; } - function checkNumericLiteral(node) { - // Grammar checking - checkGrammarNumericLiteral(node); - return numberType; - } function checkExpressionWorker(node, contextualMapper) { switch (node.kind) { case 69 /* Identifier */: @@ -27968,15 +28904,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 */: @@ -28231,16 +29165,21 @@ var ts; } } 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 */); } } } @@ -28251,21 +29190,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)); } @@ -28279,7 +29218,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 */) { @@ -28293,7 +29232,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); } @@ -28460,12 +29399,7 @@ var ts; 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 (!(node.flags & 65536 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } @@ -28494,7 +29428,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); @@ -28548,6 +29485,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) { @@ -28855,10 +29795,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 */; } @@ -28895,7 +29835,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]; @@ -28921,7 +29861,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; @@ -28939,13 +29879,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); @@ -29167,7 +30107,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 @@ -29357,22 +30297,20 @@ 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) && - !parameterIsThisKeyword(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 /* 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) { @@ -29400,7 +30338,7 @@ var ts; 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); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); } } } @@ -29430,14 +30368,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); } } } @@ -29926,7 +30862,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 { @@ -29937,7 +30873,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); @@ -30019,7 +30955,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 { @@ -30034,7 +30970,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; @@ -30060,7 +30996,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 { @@ -30075,7 +31011,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; } @@ -30097,7 +31033,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) || @@ -30125,10 +31061,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; @@ -30160,10 +31096,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; } @@ -30177,7 +31113,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 @@ -30329,7 +31265,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); @@ -30354,7 +31290,7 @@ 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]; @@ -30373,7 +31309,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]; } @@ -30398,7 +31334,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 @@ -30513,6 +31449,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 @@ -30530,15 +31471,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 { @@ -30692,7 +31633,7 @@ 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++) { @@ -30700,11 +31641,11 @@ var ts; 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)) { + 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; @@ -30745,7 +31686,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); @@ -31106,10 +32047,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)) { @@ -31171,19 +32108,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); @@ -31223,8 +32161,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 : @@ -31281,11 +32219,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); } } @@ -31335,7 +32273,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); @@ -31405,7 +32343,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); @@ -31588,9 +32526,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) { @@ -31670,7 +32609,7 @@ var ts; return false; } function getSymbolsInScope(location, meaning) { - var symbols = {}; + var symbols = ts.createMap(); var memberFlags = 0; if (isInsideWithStatementBody(location)) { // We cannot answer semantic questions within a with block, do not proceed any further @@ -31708,7 +32647,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 */: @@ -31739,7 +32678,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; } } @@ -31828,17 +32767,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; @@ -31847,14 +32784,14 @@ 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); @@ -31886,7 +32823,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 */) { @@ -31990,7 +32927,7 @@ 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)) { @@ -32104,7 +33041,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; } }); @@ -32155,7 +33092,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) { @@ -32343,7 +33280,7 @@ 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) { // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. @@ -32353,7 +33290,7 @@ var ts; 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); // 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; @@ -32365,22 +33302,22 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeOfKind(type, 16 /* Void */)) { + else if (isTypeOfKind(type, 1024 /* Void */)) { return ts.TypeReferenceSerializationKind.VoidType; } - 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)) { @@ -32416,7 +33353,7 @@ 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 || @@ -32437,9 +33374,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; @@ -32488,7 +33422,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; } @@ -32608,7 +33542,7 @@ 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"); }); @@ -32628,7 +33562,7 @@ 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; } @@ -32643,7 +33577,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 = []; @@ -32672,49 +33606,9 @@ 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; @@ -32908,6 +33802,60 @@ var ts; return checkGrammarAsyncModifier(node, lastAsync); } } + /** + * 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) { if (languageVersion < 2 /* ES6 */) { return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_2015_or_higher); @@ -33145,7 +34093,7 @@ var ts; } } function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = {}; + var seen = ts.createMap(); var Property = 1; var GetAccessor = 2; var SetAccessor = 4; @@ -33201,7 +34149,7 @@ var ts; if (effectiveName === undefined) { return "continue"; } - if (!ts.hasProperty(seen, effectiveName)) { + if (!seen[effectiveName]) { seen[effectiveName] = currentKind; } else { @@ -33229,7 +34177,7 @@ var ts; } } 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 */) { @@ -33237,7 +34185,7 @@ var ts; } var jsxAttr = attr; var name_22 = jsxAttr.name; - if (!ts.hasProperty(seen, name_22.text)) { + if (!seen[name_22.text]) { seen[name_22.text] = true; } else { @@ -33587,7 +34535,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: @@ -33605,6 +34553,7 @@ var ts; node.kind === 229 /* ImportEqualsDeclaration */ || node.kind === 236 /* ExportDeclaration */ || node.kind === 235 /* ExportAssignment */ || + node.kind === 228 /* NamespaceExportDeclaration */ || (node.flags & 2 /* Ambient */) || (node.flags & (1 /* Export */ | 512 /* Default */))) { return false; @@ -33665,7 +34614,6 @@ var ts; return true; } } - var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); @@ -33702,6 +34650,7 @@ var ts; ts.getNullSourceMapWriter = getNullSourceMapWriter; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); + var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var sourceMapDir; // The directory in which sourcemap will be var stopOverridingSpan = false; @@ -33865,6 +34814,9 @@ var ts; if (pos === -1) { return; } + if (extendedDiagnostics) { + ts.performance.mark("beforeSourcemap"); + } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); // Convert the location to be one-based. sourceLinePos.line++; @@ -33897,6 +34849,10 @@ var ts; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } updateLastEncodedAndRecordedSpans(); + if (extendedDiagnostics) { + ts.performance.mark("afterSourcemap"); + ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); + } } function getStartPos(range) { var rangeHasDecorators = !!range.decorators; @@ -34104,9 +35060,7 @@ var ts; }); if (usedTypeDirectiveReferences) { for (var directive in usedTypeDirectiveReferences) { - if (ts.hasProperty(usedTypeDirectiveReferences, directive)) { - referencesOutput += "/// " + newLine; - } + referencesOutput += "/// " + newLine; } } return { @@ -34204,11 +35158,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; } } @@ -34316,7 +35270,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); @@ -34367,7 +35321,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) { @@ -34441,14 +35395,14 @@ 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)) { + if (!(name_23 in currentIdentifiers)) { return name_23; } } @@ -34881,7 +35835,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 */) { @@ -34987,8 +35941,10 @@ 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 */) { @@ -35603,7 +36559,7 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); - var entities = { + var entities = ts.createMap({ "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -35857,7 +36813,7 @@ var ts; "clubs": 0x2663, "hearts": 0x2665, "diams": 0x2666 - }; + }); // Flags enum to track count of temp variables and a few dedicated names var TempFlags; (function (TempFlags) { @@ -35900,7 +36856,7 @@ var ts; }; 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 in node.locals) { // 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; @@ -35912,13 +36868,13 @@ var ts; function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { - state.labeledNonLocalBreaks = {}; + state.labeledNonLocalBreaks = ts.createMap(); } state.labeledNonLocalBreaks[labelText] = labelMarker; } else { if (!state.labeledNonLocalContinues) { - state.labeledNonLocalContinues = {}; + state.labeledNonLocalContinues = ts.createMap(); } state.labeledNonLocalContinues[labelText] = labelMarker; } @@ -35985,26 +36941,26 @@ var ts; /** 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 = {}, + var moduleEmitDelegates = ts.createMap((_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 = {}, + )); + var bundleEmitDelegates = ts.createMap((_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 = {}; + generatedNameSet = ts.createMap(); nodeToGeneratedName = []; decoratedClassAliases = []; isOwnFileEmit = !isBundledEmit; @@ -36066,8 +37022,8 @@ var ts; } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentFileIdentifiers, name) && - !ts.hasProperty(generatedNameSet, name); + !(name in currentFileIdentifiers) && + !(name in generatedNameSet); } // 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. @@ -37093,6 +38049,10 @@ var ts; else if (node.parent.kind === 188 /* ConditionalExpression */ && node.parent.condition === node) { return true; } + else if (node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 181 /* DeleteExpression */ || + node.parent.kind === 182 /* TypeOfExpression */ || node.parent.kind === 183 /* VoidExpression */) { + return true; + } return false; } function needsParenthesisForPropertyAccessOrInvocation(node) { @@ -37766,7 +38726,7 @@ var ts; operand.kind === 196 /* NonNullExpression */) { operand = operand.expression; } - // We have an expression of the form: (SubExpr) + // We have an expression of the form: (SubExpr) or (SubExpr as Type) // 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.: @@ -37780,6 +38740,7 @@ var ts; operand.kind !== 181 /* DeleteExpression */ && operand.kind !== 186 /* PostfixUnaryExpression */ && operand.kind !== 175 /* NewExpression */ && + !(operand.kind === 187 /* BinaryExpression */ && node.expression.kind === 195 /* AsExpression */) && !(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 */)) { @@ -37821,7 +38782,7 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, node.text); + return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 /* PlusPlusToken */ @@ -38366,12 +39327,12 @@ var ts; // 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 = {}; + seen = ts.createMap(); } else { write(", "); } - if (!ts.hasProperty(seen, id.text)) { + if (!(id.text in seen)) { emit(id); seen[id.text] = id.text; } @@ -38895,7 +39856,7 @@ var ts; } if (convertedLoopState) { if (!convertedLoopState.labels) { - convertedLoopState.labels = {}; + convertedLoopState.labels = ts.createMap(); } convertedLoopState.labels[node.label.text] = node.label.text; } @@ -38998,7 +39959,7 @@ var ts; if (modulekind === ts.ModuleKind.System) { return; } - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + if (!exportEquals && exportSpecifiers && name.text in exportSpecifiers) { for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { var specifier = _b[_a]; writeLine(); @@ -39536,12 +40497,13 @@ var ts; } function emitRestParameter(node) { if (languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; + var restParam = node.parameters[node.parameters.length - 1]; // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. if (ts.isBindingPattern(restParam.name)) { return; } + var skipThisCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; + var restIndex = node.parameters.length - 1 - skipThisCount; var tempName = createTempVariable(268435456 /* _i */).text; writeLine(); emitLeadingComments(restParam); @@ -39676,7 +40638,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var skipCount = node.parameters.length && node.parameters[0].name.text === "this" ? 1 : 0; + var skipCount = node.parameters.length && node.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; var omitCount = languageVersion < 2 /* ES6 */ && ts.hasDeclaredRestParameter(node) ? 1 : 0; emitList(parameters, skipCount, parameters.length - omitCount - skipCount, /*multiLine*/ false, /*trailingComma*/ false); } @@ -40198,18 +41160,22 @@ var ts; 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. + // 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 String "constructor( ){ }" using the syntactic grammar with the goal symbol MethodDefinition - if (baseTypeElement) { - write("(...args)"); - } - else { - write("()"); - } + // 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 below. + write("()"); } } var startIndex = 0; @@ -40243,7 +41209,8 @@ var ts; write("_super.apply(this, arguments);"); } else { - write("super(...args);"); + // See comment above on using '...arguments' instead of '...args'. + write("super(...arguments);"); } emitEnd(baseTypeElement); } @@ -40402,13 +41369,17 @@ var ts; // 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; ... } + // (class C { static a = 1; static b = 2; ... }) // // We'll emit: // - // let C_1 = class C{}; - // C_1.a = 1; - // C_1.b = 2; // so forth and so on + // ((C_1 = class C { + // // Normal class body + // }, + // C_1.a = 1, + // C_1.b = 2, + // C_1)); + // var C_1; // // This keeps the expression as an expression, while ensuring that the static parts // of it have been initialized by the time it is used. @@ -40416,7 +41387,7 @@ var ts; var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 192 /* ClassExpression */; var generatedName; if (isClassExpressionWithStaticProperties) { - generatedName = getGeneratedNameForNode(node.name); + generatedName = node.name ? getGeneratedNameForNode(node.name) : makeUniqueName("classExpression"); var synthesizedNode = ts.createSynthesizedNode(69 /* Identifier */); synthesizedNode.text = generatedName; recordTempDeclaration(synthesizedNode); @@ -40861,7 +41832,7 @@ var ts; write("Boolean"); return; case 132 /* StringKeyword */: - case 166 /* StringLiteralType */: + case 166 /* LiteralType */: write("String"); return; case 130 /* NumberKeyword */: @@ -40959,10 +41930,11 @@ var ts; } if (valueDeclaration) { var parameters = valueDeclaration.parameters; + var skipThisCount = parameters.length && parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */ ? 1 : 0; var parameterCount = parameters.length; - if (parameterCount > 0) { - for (var i = 0; i < parameterCount; i++) { - if (i > 0) { + if (parameterCount > skipThisCount) { + for (var i = skipThisCount; i < parameterCount; i++) { + if (i > skipThisCount) { write(", "); } if (parameters[i].dotDotDotToken) { @@ -41230,7 +42202,7 @@ var ts; * 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)) { + if (renamedDependencies && moduleName.text in renamedDependencies) { return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; @@ -41550,7 +42522,7 @@ var ts; } function collectExternalModuleInfo(sourceFile) { externalImports = []; - exportSpecifiers = {}; + exportSpecifiers = ts.createMap(); exportEquals = undefined; hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { @@ -41678,7 +42650,7 @@ var ts; return undefined; } // local names set should only be added if we have anything exported - if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { + if (!exportedDeclarations && !ts.someProperties(exportSpecifiers)) { // no exported declarations (export var ...) or export specifiers (export {x}) // check if we have any non star export declarations. var hasExportDeclarationWithExportClause = false; @@ -41801,7 +42773,7 @@ var ts; if (hoistedVars) { writeLine(); write("var "); - var seen = {}; + var seen = ts.createMap(); for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; var name_32 = local.kind === 69 /* Identifier */ @@ -41810,7 +42782,7 @@ var ts; 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)) { + if (text in seen) { continue; } else { @@ -42126,7 +43098,7 @@ var ts; write("System.register("); writeModuleName(node, emitRelativePathAsModuleName); write("["); - var groupIndices = {}; + var groupIndices = ts.createMap(); var dependencyGroups = []; for (var i = 0; i < externalImports.length; i++) { var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); @@ -42136,7 +43108,7 @@ var ts; // 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)) { + if (key in groupIndices) { // deduplicate/group entries in dependency list by the dependency name var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); @@ -42967,12 +43939,8 @@ var 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.1.0"; + ts.version = "2.0.2"; var emptyArray = []; var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { @@ -43064,46 +44032,26 @@ var ts; 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 @@ -43116,6 +44064,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) { @@ -43412,7 +44370,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); @@ -43557,22 +44515,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); @@ -43580,29 +44540,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) { @@ -43610,7 +44569,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; } @@ -43630,6 +44592,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); @@ -43705,15 +44670,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. @@ -43724,9 +44682,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) { @@ -43739,7 +44698,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)) { @@ -43758,11 +44717,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 && @@ -43781,7 +44740,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); @@ -43789,7 +44748,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) { @@ -43830,8 +44790,8 @@ var ts; 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]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; if (diagnostic.file) { var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; var fileName = diagnostic.file.fileName; @@ -43872,33 +44832,25 @@ var ts; return []; } var resolutions = []; - var cache = {}; + var cache = ts.createMap(); 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 result = name_34 in cache + ? cache[name_34] + : cache[name_34] = loader(name_34, 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; @@ -43911,7 +44863,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)); + } + } } } } @@ -43926,7 +44888,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: @@ -43935,14 +44897,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 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 = {}; + 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 = {}; - var start = new Date().getTime(); + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; var programDiagnostics = ts.createDiagnosticCollection(); @@ -43973,10 +44935,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]); @@ -44027,7 +44989,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") { @@ -44051,10 +45014,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; @@ -44079,7 +45042,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); @@ -44185,7 +45148,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 }; @@ -44233,9 +45196,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) { @@ -44387,16 +45351,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) { @@ -44440,8 +45404,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; @@ -44651,7 +45615,7 @@ var ts; } // 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 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) { + if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) { sourceFilesFoundSearchingNodeModules[file_1.path] = false; if (!options.noResolve) { processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib); @@ -44660,7 +45624,7 @@ var ts; modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); } - else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) { + else if (file_1 && modulesWithElidedImports[file_1.path]) { if (currentNodeModulesDepth < maxNodeModulesJsDepth) { modulesWithElidedImports[file_1.path] = false; processImportedModules(file_1, ts.getDirectoryPath(fileName)); @@ -44715,14 +45679,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) { @@ -44743,7 +45709,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; @@ -44779,7 +45745,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++) { @@ -44878,6 +45844,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; @@ -44924,7 +45893,7 @@ 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)); @@ -44935,19 +45904,19 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.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 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.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 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.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 @@ -45036,6 +46005,10 @@ var ts; name: "diagnostics", type: "boolean" }, + { + name: "extendedDiagnostics", + type: "boolean" + }, { name: "emitBOM", type: "boolean" @@ -45066,10 +46039,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 }, @@ -45096,7 +46069,7 @@ var ts; { name: "module", shortName: "m", - type: { + type: ts.createMap({ "none": ts.ModuleKind.None, "commonjs": ts.ModuleKind.CommonJS, "amd": ts.ModuleKind.AMD, @@ -45104,16 +46077,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 }, @@ -45131,6 +46104,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", @@ -45255,12 +46232,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 }, @@ -45289,10 +46266,10 @@ 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 }, { @@ -45397,7 +46374,7 @@ var ts; type: "list", element: { name: "lib", - type: { + type: ts.createMap({ // JavaScript only "es5": "lib.es5.d.ts", "es6": "lib.es2015.d.ts", @@ -45422,7 +46399,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 }, @@ -45459,14 +46436,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) { @@ -45480,9 +46464,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; @@ -45490,7 +46474,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 { @@ -45542,10 +46526,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)); @@ -45657,6 +46641,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_35 in options) { + if (ts.hasProperty(options, name_35)) { + // 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_35) { + case "init": + case "watch": + case "version": + case "help": + case "project": + break; + default: + var value = options[name_35]; + var optionDefinition = optionsNameMap[name_35.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_35] = 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_35] = convertedValue; + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result[name_35] = 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 / * * / @@ -45681,9 +46749,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 @@ -45767,7 +46832,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; } @@ -45784,7 +46849,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); } @@ -45819,7 +46884,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 { @@ -45919,11 +46984,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); } @@ -45959,16 +47024,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; } } @@ -46017,20 +47079,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_36 = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(name_36)) { continue; } - var match = wildcardDirectoryPattern.exec(name_35); + var match = wildcardDirectoryPattern.exec(name_36); 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_36) ? 1 /* Recursive */ : 0 /* None */; + var existingFlags = wildcardDirectories[key]; if (existingFlags === undefined || existingFlags < flags) { wildcardDirectories[key] = flags; if (flags === 1 /* Recursive */) { @@ -46041,12 +47103,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]; } } } @@ -46067,7 +47127,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; } } @@ -46293,12 +47353,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_36 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_36); + for (var name_37 in nameToDeclarations) { + var declarations = nameToDeclarations[name_37]; 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_37); if (!matches) { continue; } @@ -46311,14 +47371,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_36); + matches = patternMatcher.getMatches(containers, name_37); 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_37, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -46600,9 +47660,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_38 = decl.name; + if (ts.isBindingPattern(name_38)) { + addChildrenRecursively(name_38); } else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { // For `const x = function() {}`, just use the function node, not the const. @@ -46665,7 +47725,7 @@ var ts; } /** 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); @@ -46673,7 +47733,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; @@ -46916,7 +47976,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, @@ -46927,7 +47987,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, @@ -46947,49 +48007,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)) { @@ -47069,7 +48086,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); @@ -47125,7 +48142,7 @@ var ts; return totalMatch; } function getWordSpans(word) { - if (!ts.hasProperty(stringToWordSpans, word)) { + if (!(word in stringToWordSpans)) { stringToWordSpans[word] = breakIntoWordSpans(word); } return stringToWordSpans[word]; @@ -47797,7 +48814,7 @@ 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]; @@ -48354,7 +49371,7 @@ var ts; // 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) { + if (c.kind === 286 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -48548,8 +49565,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && - (previousToken.kind === 9 /* StringLiteral */ || previousToken.kind === 166 /* StringLiteralType */)) { + 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: @@ -48732,7 +49748,6 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 /* StringLiteral */ - || kind === 166 /* StringLiteralType */ || kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; @@ -49036,12 +50051,34 @@ var ts; if (host && host.getScriptKind) { scriptKind = host.getScriptKind(fileName); } - if (!scriptKind || scriptKind === 0 /* Unknown */) { + 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_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; + diagnostic.start = diagnostic.start - 1; + } + return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + } + ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; })(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. @@ -49067,7 +50104,7 @@ var ts; */ function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { // A typing name to typing file path mapping - var inferredTypings = {}; + var inferredTypings = ts.createMap(); if (!typingOptions || !typingOptions.enableAutoDiscovery) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } @@ -49075,13 +50112,7 @@ var ts; 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 = {}; - } - ; + safeList = ts.createMap(result.config); } var filesToWatch = []; // Directories to search for package.json, bower.json and other typing information @@ -49106,7 +50137,7 @@ var ts; 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]) { + if (name_39 in inferredTypings && !inferredTypings[name_39]) { inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } @@ -49135,7 +50166,7 @@ var ts; } for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { var typing = typingNames_1[_i]; - if (!ts.hasProperty(inferredTypings, typing)) { + if (!(typing in inferredTypings)) { inferredTypings[typing] = undefined; } } @@ -49149,16 +50180,16 @@ var ts; var jsonConfig = result.config; filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { - mergeTypings(ts.getKeys(jsonConfig.dependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } if (jsonConfig.devDependencies) { - mergeTypings(ts.getKeys(jsonConfig.devDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); } if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getKeys(jsonConfig.optionalDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); } if (jsonConfig.peerDependencies) { - mergeTypings(ts.getKeys(jsonConfig.peerDependencies)); + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); } } } @@ -49176,7 +50207,7 @@ var ts; mergeTypings(cleanedTypingNames); } else { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return ts.hasProperty(safeList, f); })); + 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) { @@ -49806,7 +50837,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() {} @@ -49853,6 +50884,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, @@ -49880,6 +50917,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, @@ -49913,8 +50952,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 */)); @@ -49951,10 +50990,10 @@ 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 */)); @@ -50166,12 +51205,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); }; @@ -50974,8 +52022,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; @@ -52144,7 +53193,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 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++) { @@ -52167,13 +53216,16 @@ var 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) { @@ -52642,7 +53694,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; }; @@ -52701,7 +53753,7 @@ var ts; return this.namedDeclarations; }; SourceFileObject.prototype.computeNamedDeclarations = function () { - var result = {}; + var result = ts.createMap(); ts.forEachChild(this, visit); return result; function addDeclaration(declaration) { @@ -52712,13 +53764,13 @@ var ts; } } 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_3 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_3 !== undefined) { + return result_3; } if (declaration.name.kind === 140 /* ComputedPropertyName */) { var expr = declaration.name.expression; @@ -52932,6 +53984,8 @@ var ts; ScriptElementKind.typeElement = "type"; /** enum E */ ScriptElementKind.enumElement = "enum"; + // TODO: GH#9983 + ScriptElementKind.enumMemberElement = "const"; /** * Inside module and script only * const v = .. @@ -53078,7 +54132,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 () { @@ -53190,7 +54244,7 @@ var ts; 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"; }); + return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); var _loop_3 = function(opt) { @@ -53204,7 +54258,7 @@ var ts; options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics); } else { - if (!ts.forEachValue(opt.type, function (v) { return v === value; })) { + if (!ts.forEachProperty(opt.type, function (v) { return v === value; })) { // Supplied value isn't a valid enum value. diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt)); } @@ -53256,7 +54310,9 @@ var ts; if (transpileOptions.moduleName) { sourceFile.moduleName = transpileOptions.moduleName; } - sourceFile.renamedDependencies = transpileOptions.renamedDependencies; + if (transpileOptions.renamedDependencies) { + sourceFile.renamedDependencies = ts.createMap(transpileOptions.renamedDependencies); + } var newLine = ts.getNewLineCharacter(options); // Output var outputText; @@ -53367,13 +54423,13 @@ var ts; 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 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 = ts.lookUp(buckets, key); + var bucket = buckets[key]; if (!bucket && createIfMissing) { buckets[key] = bucket = ts.createFileMap(); } @@ -53381,7 +54437,7 @@ var ts; } 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 entries = buckets[name]; var sourceFiles = []; entries.forEachValue(function (key, entry) { sourceFiles.push({ @@ -53997,7 +55053,10 @@ var ts; ts.getContainerNode = getContainerNode; /* @internal */ function getNodeKind(node) { switch (node.kind) { - case 225 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; + case 256 /* SourceFile */: + return ts.isExternalModule(node) ? ScriptElementKind.moduleElement : ScriptElementKind.scriptElement; + case 225 /* ModuleDeclaration */: + return ScriptElementKind.moduleElement; case 221 /* ClassDeclaration */: case 192 /* ClassExpression */: return ScriptElementKind.classElement; @@ -54005,11 +55064,10 @@ var ts; 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; + return getKindOfVariableDeclaration(node); + case 169 /* BindingElement */: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 180 /* ArrowFunction */: case 220 /* FunctionDeclaration */: case 179 /* FunctionExpression */: return ScriptElementKind.functionElement; @@ -54026,7 +55084,7 @@ var ts; 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 255 /* EnumMember */: return ScriptElementKind.enumMemberElement; case 142 /* Parameter */: return (node.flags & 92 /* ParameterPropertyModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; case 229 /* ImportEqualsDeclaration */: case 234 /* ImportSpecifier */: @@ -54034,8 +55092,18 @@ var ts; case 238 /* ExportSpecifier */: case 232 /* NamespaceImport */: return ScriptElementKind.alias; + case 279 /* JSDocTypedefTag */: + return ScriptElementKind.typeElement; + default: + return ScriptElementKind.unknown; + } + function getKindOfVariableDeclaration(v) { + return ts.isConst(v) + ? ScriptElementKind.constElement + : ts.isLet(v) + ? ScriptElementKind.letElement + : ScriptElementKind.variableElement; } - return ScriptElementKind.unknown; } ts.getNodeKind = getNodeKind; var CancellationTokenObject = (function () { @@ -54110,14 +55178,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, @@ -54131,7 +55201,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) { @@ -54166,7 +55235,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); } } @@ -54194,7 +55263,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) { @@ -54307,7 +55376,7 @@ var ts; 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 ((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; @@ -54343,13 +55412,13 @@ var ts; var sourceFile = getValidSourceFile(fileName); var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var isJsDocTagName = false; - var start = new Date().getTime(); + var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position); - log("getCompletionData: Get current token: " + (new Date().getTime() - start)); - start = new Date().getTime(); + 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 = isInsideComment(sourceFile, currentToken, position); - log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); + 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 @@ -54386,18 +55455,18 @@ var ts; return undefined; } } - start = new Date().getTime(); + start = ts.timestamp(); var previousToken = ts.findPrecedingToken(position, sourceFile); - log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); + 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_5 = new Date().getTime(); + var start_2 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); + 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 @@ -54440,7 +55509,7 @@ var ts; } } } - var semanticStart = new Date().getTime(); + var semanticStart = ts.timestamp(); var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -54475,7 +55544,7 @@ var ts; return undefined; } } - log("getCompletionData: Semantic work: " + (new Date().getTime() - semanticStart)); + 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 @@ -54509,7 +55578,7 @@ var ts; symbols.push(symbol); } } - if (isJavaScriptFile && type.flags & 16384 /* Union */) { + 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 @@ -54584,7 +55653,7 @@ var ts; 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 */; + var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 8388608 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); return true; } @@ -54600,12 +55669,12 @@ var ts; return scope; } function isCompletionListBlocker(contextToken) { - var start = new Date().getTime(); + var start = ts.timestamp(); var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || isSolelyIdentifierDefinitionLocation(contextToken) || isDotOfNumericLiteral(contextToken) || isInJsxText(contextToken); - log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (ts.timestamp() - start)); return result; } function isInJsxText(contextToken) { @@ -54674,16 +55743,15 @@ var ts; } 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 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_6 < position && position < end) { + if (start_3 < position && position < end) { return true; } if (position === end) { @@ -54708,7 +55776,10 @@ var ts; // 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 */) { @@ -54719,7 +55790,7 @@ var ts; // 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 - + // 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 */) { @@ -54984,7 +56055,7 @@ var ts; * do not occur at the current position and have not otherwise been typed. */ function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = {}; + 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 @@ -54994,10 +56065,10 @@ var ts; var name_41 = element.propertyName || element.name; existingImportsOrExports[name_41.text] = true; } - if (ts.isEmpty(existingImportsOrExports)) { + if (!ts.someProperties(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); }); + return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; }); } /** * Filters out completion suggestions for named imports or exports. @@ -55009,7 +56080,7 @@ var ts; if (!existingMembers || existingMembers.length === 0) { return contextualMemberSymbols; } - var existingMemberNames = {}; + 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 @@ -55038,7 +56109,7 @@ var ts; } existingMemberNames[existingName] = true; } - return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames[m.name]; }); } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. @@ -55047,7 +56118,7 @@ var ts; * do not occur at the current position and have not otherwise been typed. */ function filterJsxAttributes(symbols, attributes) { - var seenNames = {}; + 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 @@ -55058,7 +56129,7 @@ var ts; seenNames[attr.name.text] = true; } } - return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); + return ts.filter(symbols, function (a) { return !seenNames[a.name]; }); } } function getCompletionsAtPosition(fileName, position) { @@ -55107,7 +56178,7 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var target = program.getCompilerOptions().target; @@ -55166,22 +56237,22 @@ var ts; }; } function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) { - var start = new Date().getTime(); - var uniqueNames = {}; + 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 (!ts.lookUp(uniqueNames, id)) { + if (!uniqueNames[id]) { entries.push(entry); uniqueNames[id] = id; } } } } - log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); return uniqueNames; } function getStringLiteralCompletionEntries(sourceFile, position) { @@ -55189,21 +56260,55 @@ var ts; 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); + 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 { - // Otherwise, get the completions from the contextual type if one exists + 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 getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element) { + var typeChecker = program.getTypeChecker(); + 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 typeChecker = program.getTypeChecker(); var candidates = []; var entries = []; @@ -55248,11 +56353,11 @@ var ts; if (!type) { return; } - if (type.flags & 16384 /* Union */) { + if (type.flags & 524288 /* Union */) { ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); }); } else { - if (type.flags & 256 /* StringLiteral */) { + if (type.flags & 32 /* StringLiteral */) { result.push({ name: type.text, kindModifiers: ScriptElementKindModifier.none, @@ -55471,7 +56576,7 @@ var ts; displayParts.push(ts.keywordPart(92 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - if (!(type.flags & 65536 /* Anonymous */) && type.symbol) { + 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 */); @@ -55540,7 +56645,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(56 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { addNewLineIfDisplayPartsExist(); @@ -55619,7 +56724,14 @@ var ts; } if (symbolFlags & 8388608 /* Alias */) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); + 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) { @@ -55692,6 +56804,27 @@ var ts; } 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 = program.getTypeChecker().getSymbolAtLocation(declaration.parent.right); + if (!rhsSymbol) { + continue; + } + documentation = rhsSymbol.getDocumentationComment(); + if (documentation.length > 0) { + break; + } + } + } + } } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; function addNewLineIfDisplayPartsExist() { @@ -55898,7 +57031,7 @@ var ts; // Type reference directives var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { - var referenceFile = ts.lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName); + var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName]; if (referenceFile && referenceFile.resolvedFileName) { return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } @@ -55973,14 +57106,14 @@ var ts; if (!type) { return undefined; } - if (type.flags & 16384 /* Union */) { - var result_3 = []; + if (type.flags & 524288 /* Union */ && !(type.flags & 16 /* Enum */)) { + var result_4 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result_3, /*from*/ getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(/*to*/ result_4, /*from*/ getDefinitionFromSymbol(t.symbol, node)); } }); - return result_3; + return result_4; } if (!type.symbol) { return undefined; @@ -56030,14 +57163,14 @@ var ts; if (!referencedSymbols) { return undefined; } - var fileNameToDocumentHighlights = {}; + var fileNameToDocumentHighlights = ts.createMap(); 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); + var documentHighlights = fileNameToDocumentHighlights[fileName_1]; if (!documentHighlights) { documentHighlights = { fileName: fileName_1, highlightSpans: [] }; fileNameToDocumentHighlights[fileName_1] = documentHighlights; @@ -56660,7 +57793,7 @@ var ts; var sourceFile = sourceFiles_4[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName) !== undefined) { + if (nameTable[internedName] !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -57200,7 +58333,7 @@ var ts; } // 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*/ {}); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ ts.createMap()); } }); return result; @@ -57228,7 +58361,7 @@ var ts; // 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)) { + if (symbol.name in previousIterationSymbolsCache) { return; } if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -57305,9 +58438,9 @@ var ts; // 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; }); + var result_5 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_5, /*previousIterationSymbolsCache*/ ts.createMap()); + return ts.forEach(result_5, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -57328,20 +58461,20 @@ var ts; 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); + var result_6 = []; + var symbol_2 = contextualType.getProperty(name); + if (symbol_2) { + result_6.push(symbol_2); } - if (contextualType.flags & 16384 /* Union */) { + if (contextualType.flags & 524288 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_5.push(symbol); + result_6.push(symbol); } }); } - return result_5; + return result_6; } return undefined; } @@ -57580,7 +58713,6 @@ var ts; case 172 /* PropertyAccessExpression */: case 139 /* QualifiedName */: case 9 /* StringLiteral */: - case 166 /* StringLiteralType */: case 84 /* FalseKeyword */: case 99 /* TrueKeyword */: case 93 /* NullKeyword */: @@ -57934,6 +59066,9 @@ var ts; * 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; } @@ -58016,7 +59151,7 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */ || tokenKind === 166 /* StringLiteralType */) { + else if (tokenKind === 9 /* StringLiteral */) { return token.parent.kind === 246 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { @@ -58135,12 +59270,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) { @@ -58440,9 +59575,9 @@ var ts; } } function getStringLiteralTypeForNode(node, typeChecker) { - var searchNode = node.parent.kind === 166 /* StringLiteralType */ ? node.parent : node; + var searchNode = node.parent.kind === 166 /* LiteralType */ ? node.parent : node; var type = typeChecker.getTypeAtLocation(searchNode); - if (type && type.flags & 256 /* StringLiteral */) { + if (type && type.flags & 32 /* StringLiteral */) { return type; } return undefined; @@ -58588,7 +59723,7 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = {}; + var nameTable = ts.createMap(); walk(sourceFile); sourceFile.nameTable = nameTable; function walk(node) { @@ -58692,7 +59827,7 @@ var ts; 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 length_4 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -58701,8 +59836,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); } } - entries.push({ length: length_3, classification: convertClassification(type) }); - lastEnd = start + length_3; + entries.push({ length: length_4, classification: convertClassification(type) }); + lastEnd = start + length_4; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -58882,7 +60017,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9 /* StringLiteral */ || token === 166 /* StringLiteralType */) { + if (token === 9 /* StringLiteral */) { // Check to see if we finished up on a multiline string literal. var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { @@ -59021,7 +60156,6 @@ var ts; case 8 /* NumericLiteral */: return 4 /* numericLiteral */; case 9 /* StringLiteral */: - case 166 /* StringLiteralType */: return 6 /* stringLiteral */; case 10 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; @@ -59742,7 +60876,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; }); }; @@ -59753,7 +60887,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); }); }; } } @@ -59846,7 +60980,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. @@ -59899,6 +61033,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; @@ -59906,11 +61043,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; @@ -60296,6 +61433,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; @@ -60431,5 +61575,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.0"; /* tslint:enable:no-unused-variable */ diff --git a/package.json b/package.json index eb34b6bffbb..b0669aadad6 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "http://typescriptlang.org/", - "version": "2.1.0", + "version": "2.0.2", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 8568cd5feed..d38ce359e8b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -106,7 +106,7 @@ namespace ts { isOptionalParameter }; - const tupleTypes = createMap(); + const tupleTypes: GenericType[] = []; const unionTypes = createMap(); const intersectionTypes = createMap(); const stringLiteralTypes = createMap(); @@ -1023,8 +1023,8 @@ namespace ts { } } - function getDeclarationOfAliasSymbol(symbol: Symbol): Declaration { - return findMap(symbol.declarations, d => isAliasSymbolDeclaration(d) ? d : undefined); + function getDeclarationOfAliasSymbol(symbol: Symbol): Declaration | undefined { + return forEach(symbol.declarations, d => isAliasSymbolDeclaration(d) ? d : undefined); } function getTargetOfImportEqualsDeclaration(node: ImportEqualsDeclaration): Symbol { @@ -1126,13 +1126,13 @@ namespace ts { else { symbolFromVariable = getPropertyOfVariable(targetSymbol, name.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 (!symbolFromVariable && allowSyntheticDefaultImports && name.text === "default") { - symbolFromVariable = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); - } // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable); - const symbolFromModule = getExportOfModule(targetSymbol, name.text); + let symbolFromModule = getExportOfModule(targetSymbol, name.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.text === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } const symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; @@ -1191,6 +1191,7 @@ namespace ts { if (!links.target) { links.target = resolvingSymbol; const node = getDeclarationOfAliasSymbol(symbol); + Debug.assert(!!node); const target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -1226,6 +1227,7 @@ namespace ts { if (!links.referenced) { links.referenced = true; const node = getDeclarationOfAliasSymbol(symbol); + Debug.assert(!!node); if (node.kind === SyntaxKind.ExportAssignment) { // export default checkExpressionCached((node).expression); @@ -2145,9 +2147,6 @@ namespace ts { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, nextFlags); } - else if (type.flags & TypeFlags.Tuple) { - writeTupleType(type); - } else if (!(flags & TypeFormatFlags.InTypeAlias) && type.flags & (TypeFlags.Anonymous | TypeFlags.UnionOrIntersection) && type.aliasSymbol) { const typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); @@ -2214,6 +2213,11 @@ namespace ts { writePunctuation(writer, SyntaxKind.OpenBracketToken); writePunctuation(writer, SyntaxKind.CloseBracketToken); } + else if (type.target.flags & TypeFlags.Tuple) { + writePunctuation(writer, SyntaxKind.OpenBracketToken); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), SyntaxKind.CommaToken); + writePunctuation(writer, SyntaxKind.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 @@ -2242,12 +2246,6 @@ namespace ts { } } - function writeTupleType(type: TupleType) { - writePunctuation(writer, SyntaxKind.OpenBracketToken); - writeTypeList(type.elementTypes, SyntaxKind.CommaToken); - writePunctuation(writer, SyntaxKind.CloseBracketToken); - } - function writeUnionOrIntersectionType(type: UnionOrIntersectionType, flags: TypeFormatFlags) { if (flags & TypeFormatFlags.InElementType) { writePunctuation(writer, SyntaxKind.OpenParenToken); @@ -2958,7 +2956,7 @@ namespace ts { : elementType; if (!type) { if (isTupleType(parentType)) { - error(declaration, 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, 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, Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); @@ -3070,9 +3068,14 @@ namespace ts { } } // Use contextual parameter type if one is available - const type = declaration.symbol.name === "this" - ? getContextuallyTypedThisType(func) - : getContextuallyTypedParameterType(declaration); + let type: Type; + if (declaration.symbol.name === "this") { + const thisParameter = getContextualThisParameter(func); + type = thisParameter ? getTypeOfSymbol(thisParameter) : undefined; + } + else { + type = getContextuallyTypedParameterType(declaration); + } if (type) { return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } @@ -3150,12 +3153,13 @@ namespace ts { } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. const elementTypes = map(elements, e => e.kind === SyntaxKind.OmittedExpression ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors)); + let result = createTupleType(elementTypes); + if (includePatternInType) { - const 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 @@ -3564,18 +3568,21 @@ namespace ts { } function getBaseTypes(type: InterfaceType): ObjectType[] { - const isClass = type.symbol.flags & SymbolFlags.Class; - const isInterface = type.symbol.flags & SymbolFlags.Interface; if (!type.resolvedBaseTypes) { - if (!isClass && !isInterface) { + if (type.flags & TypeFlags.Tuple) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + } + else if (type.symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) { + if (type.symbol.flags & SymbolFlags.Class) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & SymbolFlags.Interface) { + resolveBaseTypesOfInterface(type); + } + } + else { Debug.fail("type must be class or interface"); } - if (isClass) { - resolveBaseTypesOfClass(type); - } - if (isInterface) { - resolveBaseTypesOfInterface(type); - } } return type.resolvedBaseTypes; } @@ -4001,20 +4008,25 @@ namespace ts { return createTypeReference((type).target, concatenate((type).typeArguments, [thisArgument || (type).target.thisType])); } - if (type.flags & TypeFlags.Tuple) { - return createTupleType((type as TupleType).elementTypes, thisArgument); - } return type; } function resolveObjectTypeMembers(type: ObjectType, source: InterfaceTypeWithDeclaredMembers, typeParameters: TypeParameter[], typeArguments: Type[]) { - let mapper = identityMapper; - let members = source.symbol.members; - let callSignatures = source.declaredCallSignatures; - let constructSignatures = source.declaredConstructSignatures; - let stringIndexInfo = source.declaredStringIndexInfo; - let numberIndexInfo = source.declaredNumberIndexInfo; - if (!rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + let mapper: TypeMapper; + let members: SymbolTable; + let callSignatures: Signature[]; + let constructSignatures: Signature[]; + let stringIndexInfo: IndexInfo; + let numberIndexInfo: IndexInfo; + if (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); @@ -4024,7 +4036,7 @@ namespace ts { } const baseTypes = getBaseTypes(source); if (baseTypes.length) { - if (members === source.symbol.members) { + if (source.symbol && members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } const thisArgument = lastOrUndefined(typeArguments); @@ -4094,26 +4106,6 @@ namespace ts { return result; } - function createTupleTypeMemberSymbols(memberTypes: Type[]): SymbolTable { - const members = createMap(); - for (let i = 0; i < memberTypes.length; i++) { - const symbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "" + i); - symbol.type = memberTypes[i]; - members[i] = symbol; - } - return members; - } - - function resolveTupleTypeMembers(type: TupleType) { - const arrayElementType = getUnionType(type.elementTypes); - // Make the tuple type itself the 'this' type by including an extra type argument - // (Unless it's provided in the case that the tuple is a type parameter constraint) - const arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type.thisType || type])); - const members = createTupleTypeMemberSymbols(type.elementTypes); - addInheritedMembers(members, arrayType.properties); - setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); - } - function findMatchingSignature(signatureList: Signature[], signature: Signature, partialMatch: boolean, ignoreThisTypes: boolean, ignoreReturnTypes: boolean): Signature { for (const s of signatureList) { if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { @@ -4292,9 +4284,6 @@ namespace ts { else if (type.flags & TypeFlags.Anonymous) { resolveAnonymousTypeMembers(type); } - else if (type.flags & TypeFlags.Tuple) { - resolveTupleTypeMembers(type); - } else if (type.flags & TypeFlags.Union) { resolveUnionTypeMembers(type); } @@ -4694,6 +4683,9 @@ namespace ts { if (isJSConstructSignature) { minArgumentCount--; } + if (!thisParameter && isObjectLiteralMethod(declaration)) { + thisParameter = getContextualThisParameter(declaration); + } const classType = declaration.kind === SyntaxKind.Constructor ? getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent).symbol)) @@ -4992,6 +4984,17 @@ namespace ts { return type; } + function cloneTypeReference(source: TypeReference): TypeReference { + const type = createObjectType(source.flags, source.symbol); + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + + function getTypeReferenceArity(type: TypeReference): number { + return type.target.typeParameters ? type.target.typeParameters.length : 0; + } + // Get type from reference to class or interface function getTypeFromClassOrInterfaceReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol): Type { const type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); @@ -5234,17 +5237,47 @@ namespace ts { return links.resolvedType; } - function createTupleType(elementTypes: Type[], thisType?: Type) { - const id = getTypeListId(elementTypes) + "," + (thisType ? thisType.id : 0); - return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes, thisType)); + // 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: number): GenericType { + const typeParameters: TypeParameter[] = []; + const properties: Symbol[] = []; + for (let i = 0; i < arity; i++) { + const typeParameter = createType(TypeFlags.TypeParameter); + typeParameters.push(typeParameter); + const property = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "" + i); + property.type = typeParameter; + properties.push(property); + } + const type = createObjectType(TypeFlags.Tuple | TypeFlags.Reference); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = createMap(); + type.instantiations[getTypeListId(type.typeParameters)] = type; + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(TypeFlags.TypeParameter | TypeFlags.ThisType); + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = emptyArray; + type.declaredConstructSignatures = emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + return type; } - function createNewTupleType(elementTypes: Type[], thisType?: Type) { - const propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, /*excludeKinds*/ 0); - const type = createObjectType(TypeFlags.Tuple | propagatedFlags); - type.elementTypes = elementTypes; - type.thisType = thisType; - return type; + function getTupleTypeOfArity(arity: number): GenericType { + return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + } + + function createTupleType(elementTypes: Type[]) { + return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); } function getTypeFromTupleTypeNode(node: TupleTypeNode): Type { @@ -5552,6 +5585,12 @@ namespace ts { return nullType; case SyntaxKind.NeverKeyword: return neverType; + case SyntaxKind.JSDocNullKeyword: + return nullType; + case SyntaxKind.JSDocUndefinedKeyword: + return undefinedType; + case SyntaxKind.JSDocNeverKeyword: + return neverType; case SyntaxKind.ThisType: case SyntaxKind.ThisKeyword: return getTypeFromThisTypeNode(node); @@ -5845,9 +5884,6 @@ namespace ts { if (type.flags & TypeFlags.Reference) { return createTypeReference((type).target, instantiateList((type).typeArguments, mapper, instantiateType)); } - if (type.flags & TypeFlags.Tuple) { - return createTupleType(instantiateList((type).elementTypes, mapper, instantiateType)); - } if (type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Primitive)) { return getUnionType(instantiateList((type).types, mapper, instantiateType), /*subtypeReduction*/ false, type.aliasSymbol, mapper.targetTypes); } @@ -6267,6 +6303,18 @@ namespace ts { reportError(message, sourceType, targetType); } + function tryElaborateErrorsForPrimitivesAndObjects(source: Type, target: Type) { + const sourceType = typeToString(source); + const targetType = typeToString(target); + + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType() === source && esSymbolType === target)) { + reportError(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 @@ -6390,6 +6438,9 @@ namespace ts { } if (reportErrors) { + if (source.flags & TypeFlags.ObjectType && target.flags & TypeFlags.Primitive) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } reportRelationError(headMessage, source, target); } return Ternary.False; @@ -7168,8 +7219,8 @@ namespace ts { * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ - function isTupleType(type: Type): type is TupleType { - return !!(type.flags & TypeFlags.Tuple); + function isTupleType(type: Type): boolean { + return !!(type.flags & TypeFlags.Reference && (type).target.flags & TypeFlags.Tuple); } function getFalsyFlagsOfTypes(types: Type[]): TypeFlags { @@ -7301,11 +7352,8 @@ namespace ts { if (type.flags & TypeFlags.Union) { return getUnionType(map((type).types, getWidenedConstituentType)); } - if (isArrayType(type)) { - return createArrayType(getWidenedType((type).typeArguments[0])); - } - if (isTupleType(type)) { - return createTupleType(map(type.elementTypes, getWidenedType)); + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference((type).target, map((type).typeArguments, getWidenedType)); } } return type; @@ -7331,11 +7379,8 @@ namespace ts { } } } - if (isArrayType(type)) { - return reportWideningErrorsInType((type).typeArguments[0]); - } - if (isTupleType(type)) { - for (const t of type.elementTypes) { + if (isArrayType(type) || isTupleType(type)) { + for (const t of (type).typeArguments) { if (reportWideningErrorsInType(t)) { errorReported = true; } @@ -7445,7 +7490,6 @@ namespace ts { function couldContainTypeParameters(type: Type): boolean { return !!(type.flags & TypeFlags.TypeParameter || type.flags & TypeFlags.Reference && forEach((type).typeArguments, couldContainTypeParameters) || - type.flags & TypeFlags.Tuple && forEach((type).elementTypes, couldContainTypeParameters) || type.flags & TypeFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class) || type.flags & TypeFlags.UnionOrIntersection && couldUnionOrIntersectionContainTypeParameters(type)); } @@ -7548,14 +7592,6 @@ namespace ts { inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (source.flags & TypeFlags.Tuple && target.flags & TypeFlags.Tuple && (source).elementTypes.length === (target).elementTypes.length) { - // If source and target are tuples of the same size, infer from element types - const sourceTypes = (source).elementTypes; - const targetTypes = (target).elementTypes; - for (let i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - } else if (target.flags & TypeFlags.UnionOrIntersection) { const targetTypes = (target).types; let typeParameterCount = 0; @@ -9100,10 +9136,6 @@ namespace ts { return getInferredClassType(classSymbol); } } - const type = getContextuallyTypedThisType(container); - if (type) { - return type; - } const thisType = getThisTypeOfDeclaration(container); if (thisType) { @@ -9344,11 +9376,11 @@ namespace ts { } } - function getContextuallyTypedThisType(func: FunctionLikeDeclaration): Type { + function getContextualThisParameter(func: FunctionLikeDeclaration): Symbol { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== SyntaxKind.ArrowFunction) { const contextualSignature = getContextualSignature(func); if (contextualSignature) { - return getThisTypeOfSignature(contextualSignature); + return contextualSignature.thisParameter; } } @@ -9913,7 +9945,7 @@ namespace 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) { - const type = createNewTupleType(elementTypes); + const type = cloneTypeReference(createTupleType(elementTypes)); type.pattern = node; return type; } @@ -9927,7 +9959,7 @@ namespace ts { for (let i = elementTypes.length; i < patternElements.length; i++) { const patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push((contextualType).elementTypes[i]); + elementTypes.push((contextualType).typeArguments[i]); } else { if (patternElement.kind !== SyntaxKind.OmittedExpression) { @@ -12291,6 +12323,12 @@ namespace ts { function assignContextualParameterTypes(signature: Signature, context: Signature, mapper: TypeMapper) { const 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 (let i = 0; i < len; i++) { const parameter = signature.parameters[i]; const contextualParameterType = getTypeAtPosition(context, i); @@ -13038,7 +13076,7 @@ namespace ts { // such as NodeCheckFlags.LexicalThis on "this"expression. checkExpression(element); if (isTupleType(sourceType)) { - error(element, Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), (sourceType).elementTypes.length, elements.length); + error(element, Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); } else { error(element, Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); @@ -18515,7 +18553,7 @@ namespace ts { else if (isTypeOfKind(type, TypeFlags.StringLike)) { return TypeReferenceSerializationKind.StringLikeType; } - else if (isTypeOfKind(type, TypeFlags.Tuple)) { + else if (isTupleType(type)) { return TypeReferenceSerializationKind.ArrayLikeType; } else if (isTypeOfKind(type, TypeFlags.ESSymbol)) { diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 682a434e6ab..90c4d18289a 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -672,10 +672,10 @@ namespace ts { * @param fileName The path to the config file * @param jsonText The text of the config file */ - export function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic } { + export function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments = true): { config?: any; error?: Diagnostic } { try { - const jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + const jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: createCompilerDiagnostic(Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -901,7 +901,7 @@ namespace ts { function convertCompilerOptionsFromJsonWorker(jsonOptions: any, basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions { - const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; + const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_compiler_option_0, errors); return options; } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index cab5c21ad90..479c04bfeff 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -2091,8 +2091,10 @@ namespace ts { const typesFile = tryReadTypesSection(packageJsonPath, candidate, state); if (typesFile) { const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(typesFile), state.host); - // The package.json "typings" property must specify the file with extension, so just try that exact filename. - const result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures, state); + // A package.json "typings" may specify an exact filename, or may choose to omit an extension. + const result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures, state); + if (result) { return result; } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 648df9a702d..254da839a1e 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -1132,8 +1132,10 @@ namespace 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 === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || node.kind === SyntaxKind.Parameter) && 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 === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || + (node.kind === SyntaxKind.Parameter && !isParameterPropertyDeclaration(node))) && hasQuestionToken(node)) { write("?"); } if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && node.parent.kind === SyntaxKind.TypeLiteral) { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 6210a20afa6..b8978b32571 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1955,6 +1955,10 @@ "category": "Error", "code": 2691 }, + "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible.": { + "category": "Error", + "code": 2692 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", "code": 4000 diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index c3fac679048..40c806198ab 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1817,6 +1817,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge else if (node.parent.kind === SyntaxKind.ConditionalExpression && (node.parent).condition === node) { return true; } + else if (node.parent.kind === SyntaxKind.PrefixUnaryExpression || node.parent.kind === SyntaxKind.DeleteExpression || + node.parent.kind === SyntaxKind.TypeOfExpression || node.parent.kind === SyntaxKind.VoidExpression) { + return true; + } return false; } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 3e20f899c2d..fd6403cf14b 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -913,7 +913,7 @@ namespace ts { // 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. const saveContextFlags = contextFlags; // If we're only looking ahead, then tell the scanner to only lookahead as well. @@ -2766,7 +2766,7 @@ namespace 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(); } @@ -3374,24 +3374,40 @@ namespace ts { } /** - * 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(): UnaryExpression | BinaryExpression { - 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()) { const incrementExpression = parseIncrementExpression(); return token() === SyntaxKind.AsteriskAsteriskToken ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } + /** + * 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] + */ const unaryOperator = token(); const simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === SyntaxKind.AsteriskAsteriskToken) { @@ -3409,8 +3425,8 @@ namespace 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] @@ -3433,13 +3449,15 @@ namespace ts { return parseTypeOfExpression(); case SyntaxKind.VoidKeyword: return parseVoidExpression(); - case SyntaxKind.AwaitKeyword: - return parseAwaitExpression(); case SyntaxKind.LessThanToken: // This is modified UnaryExpression grammar in TypeScript // UnaryExpression (modified): // < type > UnaryExpression return parseTypeAssertion(); + case SyntaxKind.AwaitKeyword: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } default: return parseIncrementExpression(); } @@ -3448,14 +3466,14 @@ namespace 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(): boolean { + function isUpdateExpression(): boolean { // This function is called inside parseUnaryExpression to decide // whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly switch (token()) { @@ -3466,6 +3484,7 @@ namespace ts { case SyntaxKind.DeleteKeyword: case SyntaxKind.TypeOfKeyword: case SyntaxKind.VoidKeyword: + case SyntaxKind.AwaitKeyword: return false; case SyntaxKind.LessThanToken: // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression @@ -5894,6 +5913,9 @@ namespace ts { case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.VoidKeyword: + case SyntaxKind.NullKeyword: + case SyntaxKind.UndefinedKeyword: + case SyntaxKind.NeverKeyword: return parseTokenNode(); case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 932f400660f..31d87f1a6c0 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -4,7 +4,8 @@ namespace ts { /** The version of the TypeScript compiler release */ - export const version = "2.1.0"; + + export const version = "2.0.2"; const emptyArray: any[] = []; @@ -465,7 +466,7 @@ namespace 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. - const maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2; + const maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; let currentNodeModulesDepth = 0; // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 202f45eb153..9d3f419cbb2 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -352,6 +352,9 @@ namespace ts { JSDocPropertyTag, JSDocTypeLiteral, JSDocLiteralType, + JSDocNullKeyword, + JSDocUndefinedKeyword, + JSDocNeverKeyword, // Synthesized list SyntaxList, @@ -384,7 +387,7 @@ namespace ts { FirstJSDocNode = JSDocTypeExpression, LastJSDocNode = JSDocLiteralType, FirstJSDocTagNode = JSDocComment, - LastJSDocTagNode = JSDocLiteralType + LastJSDocTagNode = JSDocNeverKeyword } export const enum NodeFlags { @@ -2265,7 +2268,7 @@ namespace ts { Class = 1 << 15, // Class Interface = 1 << 16, // Interface Reference = 1 << 17, // Generic type reference - Tuple = 1 << 18, // Tuple + Tuple = 1 << 18, // Synthesized generic tuple type Union = 1 << 19, // Union (T | U) Intersection = 1 << 20, // Intersection (T & U) Anonymous = 1 << 21, // Anonymous @@ -2387,11 +2390,6 @@ namespace ts { instantiations: Map; // Generic instantiation cache } - export interface TupleType extends ObjectType { - elementTypes: Type[]; // Element types - thisType?: Type; // This-type of tuple (only needed for tuples that are constraints of type parameters) - } - export interface UnionOrIntersectionType extends Type { types: Type[]; // Constituent types /* @internal */ diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index b4e4418dac2..2925b403dd7 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -301,6 +301,10 @@ namespace ts { return node.kind >= SyntaxKind.FirstJSDocNode && node.kind <= SyntaxKind.LastJSDocNode; } + export function isJSDocTag(node: Node) { + return node.kind >= SyntaxKind.FirstJSDocTagNode && node.kind <= SyntaxKind.LastJSDocTagNode; + } + export function getNonDecoratorTokenPosOfNode(node: Node, sourceFile?: SourceFile): number { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); diff --git a/src/harness/rwcRunner.ts b/src/harness/rwcRunner.ts index d56e8d6d35f..ba1ab71ec19 100644 --- a/src/harness/rwcRunner.ts +++ b/src/harness/rwcRunner.ts @@ -158,13 +158,13 @@ namespace RWC { it("has the expected emitted code", () => { - Harness.Baseline.runBaseline(baseName + ".output.js", () => { + Harness.Baseline.runBaseline(`${baseName}.output.js`, () => { return Harness.Compiler.collateOutputs(compilerResult.files); }, baselineOpts); }); it("has the expected declaration file content", () => { - Harness.Baseline.runBaseline(baseName + ".d.ts", () => { + Harness.Baseline.runBaseline(`${baseName}.d.ts`, () => { if (!compilerResult.declFilesCode.length) { return null; } @@ -174,7 +174,7 @@ namespace RWC { }); it("has the expected source maps", () => { - Harness.Baseline.runBaseline(baseName + ".map", () => { + Harness.Baseline.runBaseline(`${baseName}.map`, () => { if (!compilerResult.sourceMaps.length) { return null; } @@ -192,7 +192,7 @@ namespace RWC { });*/ it("has the expected errors", () => { - Harness.Baseline.runBaseline(baseName + ".errors.txt", () => { + Harness.Baseline.runBaseline(`${baseName}.errors.txt`, () => { if (compilerResult.errors.length === 0) { return null; } @@ -207,7 +207,7 @@ namespace RWC { // declaration file errors as part of the baseline. it("has the expected errors in generated declaration files", () => { if (compilerOptions.declaration && !compilerResult.errors.length) { - Harness.Baseline.runBaseline(baseName + ".dts.errors.txt", () => { + Harness.Baseline.runBaseline(`${baseName}.dts.errors.txt`, () => { const declFileCompilationResult = Harness.Compiler.compileDeclarationFiles( inputFiles, otherFiles, compilerResult, /*harnessSettings*/ undefined, compilerOptions, currentDirectory); @@ -223,7 +223,7 @@ namespace RWC { }); it("has the expected types", () => { - Harness.Compiler.doTypeAndSymbolBaseline(baseName, compilerResult, inputFiles + Harness.Compiler.doTypeAndSymbolBaseline(`${baseName}.types`, compilerResult, inputFiles .concat(otherFiles) .filter(file => !!compilerResult.program.getSourceFile(file.unitName)) .filter(e => !Harness.isDefaultLibraryFile(e.unitName)), baselineOpts); diff --git a/src/harness/unittests/convertCompilerOptionsFromJson.ts b/src/harness/unittests/convertCompilerOptionsFromJson.ts index d308bb2a6e6..9de18850477 100644 --- a/src/harness/unittests/convertCompilerOptionsFromJson.ts +++ b/src/harness/unittests/convertCompilerOptionsFromJson.ts @@ -403,6 +403,7 @@ namespace ts { { compilerOptions: { allowJs: true, + maxNodeModuleJsDepth: 2, module: ModuleKind.CommonJS, target: ScriptTarget.ES5, noImplicitAny: false, @@ -429,6 +430,7 @@ namespace ts { { compilerOptions: { allowJs: false, + maxNodeModuleJsDepth: 2, module: ModuleKind.CommonJS, target: ScriptTarget.ES5, noImplicitAny: false, @@ -450,7 +452,8 @@ namespace ts { { compilerOptions: { - allowJs: true + allowJs: true, + maxNodeModuleJsDepth: 2 }, errors: [{ file: undefined, @@ -469,7 +472,8 @@ namespace ts { { compilerOptions: { - allowJs: true + allowJs: true, + maxNodeModuleJsDepth: 2 }, errors: [] } diff --git a/src/harness/unittests/jsDocParsing.ts b/src/harness/unittests/jsDocParsing.ts index d1ca42f3861..a9987ef3176 100644 --- a/src/harness/unittests/jsDocParsing.ts +++ b/src/harness/unittests/jsDocParsing.ts @@ -767,16 +767,9 @@ namespace ts { parsesCorrectly( "{null}", `{ - "kind": "JSDocTypeReference", + "kind": "NullKeyword", "pos": 1, - "end": 5, - "name": { - "kind": "Identifier", - "pos": 1, - "end": 5, - "originalKeywordKind": "NullKeyword", - "text": "null" - } + "end": 5 }`); }); @@ -784,16 +777,9 @@ namespace ts { parsesCorrectly( "{undefined}", `{ - "kind": "JSDocTypeReference", + "kind": "UndefinedKeyword", "pos": 1, - "end": 10, - "name": { - "kind": "Identifier", - "pos": 1, - "end": 10, - "originalKeywordKind": "UndefinedKeyword", - "text": "undefined" - } + "end": 10 }`); }); @@ -2379,4 +2365,4 @@ namespace ts { }); }); }); -} \ No newline at end of file +} diff --git a/src/harness/unittests/tsconfigParsing.ts b/src/harness/unittests/tsconfigParsing.ts index 557379dff3b..e552faf2e88 100644 --- a/src/harness/unittests/tsconfigParsing.ts +++ b/src/harness/unittests/tsconfigParsing.ts @@ -181,5 +181,26 @@ namespace ts { ["/d.ts", "/folder/e.ts"] ); }); + + it("parse and re-emit tsconfig.json file with diagnostics", () => { + const content = `{ + "compilerOptions": { + "allowJs": true + // Some comments + "outDir": "bin" + } + "files": ["file1.ts"] + }`; + const { configJsonObject, diagnostics } = sanitizeConfigFile("config.json", content); + const expectedResult = { + compilerOptions: { + allowJs: true, + outDir: "bin" + }, + files: ["file1.ts"] + }; + assert.isTrue(diagnostics.length === 2); + assert.equal(JSON.stringify(configJsonObject), JSON.stringify(expectedResult)); + }); }); } diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index 813ea189157..362b477c80f 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -832,6 +832,23 @@ namespace ts { checkNumberOfConfiguredProjects(projectService, 1); checkNumberOfInferredProjects(projectService, 0); }); + it("should tolerate config file errors and still try to build a project", () => { + const configFile: FileOrFolder = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": { + "target": "es6", + "allowAnything": true + }, + "someOtherProperty": {} + }` + }; + const host = createServerHost([commonFile1, commonFile2, libFile, configFile]); + const projectService = createProjectService(host); + projectService.openClientFile(commonFile1.path); + checkNumberOfConfiguredProjects(projectService, 1); + checkProjectRootFiles(projectService.configuredProjects[0], [commonFile1.path, commonFile2.path]); + }); it("should use only one inferred project if 'useOneInferredProject' is set", () => { const file1 = { @@ -2273,10 +2290,15 @@ namespace ts { projectService.openClientFile(file1.path); { - projectService.checkNumberOfProjects({ inferredProjects: 1, configuredProjects: 1 }); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); const configuredProject = forEach(projectService.synchronizeProjectList([]), f => f.info.projectName === corruptedConfig.path && f); assert.isTrue(configuredProject !== undefined, "should find configured project"); - checkProjectErrors(configuredProject, [`Failed to parse file \'/a/b/tsconfig.json\': Unexpected token : in JSON at position 7.`]); + checkProjectErrors(configuredProject, [ + "')' expected.", + "Declaration or statement expected.", + "Declaration or statement expected.", + "Failed to parse file '/a/b/tsconfig.json': Unexpected token ) in JSON at position 7." + ]); } // fix config and trigger watcher host.reloadFS([file1, file2, correctConfig]); @@ -2316,14 +2338,19 @@ namespace ts { assert.isTrue(configuredProject !== undefined, "should find configured project"); checkProjectErrors(configuredProject, []); } - // fix config and trigger watcher + // break config and trigger watcher host.reloadFS([file1, file2, corruptedConfig]); host.triggerFileWatcherCallback(corruptedConfig.path, /*false*/); { - projectService.checkNumberOfProjects({ inferredProjects: 1, configuredProjects: 1 }); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); const configuredProject = forEach(projectService.synchronizeProjectList([]), f => f.info.projectName === corruptedConfig.path && f); assert.isTrue(configuredProject !== undefined, "should find configured project"); - checkProjectErrors(configuredProject, [`Failed to parse file \'/a/b/tsconfig.json\': Unexpected token : in JSON at position 7.`]); + checkProjectErrors(configuredProject, [ + "')' expected.", + "Declaration or statement expected.", + "Declaration or statement expected.", + "Failed to parse file '/a/b/tsconfig.json': Unexpected token ) in JSON at position 7." + ]); } }); }); @@ -2342,23 +2369,10 @@ namespace ts { const projectService = createProjectService(host); projectService.openClientFile(file1.path); - projectService.checkNumberOfProjects({ inferredProjects: 1, configuredProjects: 1 }); + projectService.checkNumberOfProjects({ configuredProjects: 1 }); const project = projectService.findProject(corruptedConfig.path); - let expectedMessage: string; - try { - server.Errors.ThrowProjectDoesNotContainDocument(file1.path, project); - assert(false, "should not get there"); - } - catch (e) { - expectedMessage = (e).message; - } - try { - project.getScriptInfo(file1.path); - } - catch (e) { - assert.equal((e).message, expectedMessage, "Unexpected error"); - } + checkProjectRootFiles(project, [file1.path]); }); }); } \ No newline at end of file diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index d2938f6e983..ee657f64a65 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -126,6 +126,7 @@ interface KeyAlgorithm { } interface KeyboardEventInit extends EventModifierInit { + code?: string; key?: string; location?: number; repeat?: boolean; @@ -2288,7 +2289,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. */ @@ -3351,7 +3352,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; } @@ -3420,7 +3421,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; @@ -3675,6 +3676,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; @@ -4446,7 +4457,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: { @@ -4621,11 +4632,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; @@ -5890,6 +5897,7 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { */ type: string; import?: Document; + integrity: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6178,7 +6186,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; /** @@ -6751,6 +6759,7 @@ interface HTMLScriptElement extends HTMLElement { * Sets or retrieves the MIME type for the associated scripting engine. */ type: string; + integrity: string; } declare var HTMLScriptElement: { @@ -7756,6 +7765,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; @@ -9128,6 +9138,7 @@ interface PerformanceTiming { readonly responseStart: number; readonly unloadEventEnd: number; readonly unloadEventStart: number; + readonly secureConnectionStart: number; toJSON(): any; } @@ -11405,8 +11416,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; @@ -12947,7 +12958,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; @@ -13002,6 +13013,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; @@ -14029,6 +14043,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; @@ -14072,7 +14100,7 @@ interface EcdsaParams extends Algorithm { } interface EcKeyGenParams extends Algorithm { - typedCurve: string; + namedCurve: string; } interface EcKeyAlgorithm extends KeyAlgorithm { @@ -14208,6 +14236,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 { @@ -14278,7 +14313,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; @@ -14372,7 +14407,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; @@ -14425,6 +14460,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; @@ -14580,6 +14618,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/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index c61a1a8b8a6..483348f3f75 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -1000,7 +1000,7 @@ interface EcdsaParams extends Algorithm { } interface EcKeyGenParams extends Algorithm { - typedCurve: string; + namedCurve: string; } interface EcKeyAlgorithm extends KeyAlgorithm { diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 267165f2657..dbaeb4b45c9 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -11,6 +11,13 @@ namespace ts.server { export const maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + export type ProjectServiceEvent = + { eventName: "context", data: { project: Project, fileName: NormalizedPath } } | { eventName: "configFileDiag", data: { triggerFile?: string, configFileName: string, diagnostics: Diagnostic[] } } + + export interface ProjectServiceEventHandler { + (event: ProjectServiceEvent): void; + } + /** * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. */ @@ -19,10 +26,6 @@ namespace ts.server { return projects.length > 1 ? deduplicate(result, areEqual) : result; } - export interface ProjectServiceEventHandler { - (eventName: string, project: Project, fileName: NormalizedPath): void; - } - export interface HostConfiguration { formatCodeOptions: FormatCodeSettings; hostInfo: string; @@ -348,7 +351,7 @@ namespace ts.server { } for (const openFile of this.openFiles) { - this.eventHandler("context", openFile.getDefaultProject(), openFile.fileName); + this.eventHandler({ eventName: "context", data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } }); } } @@ -376,7 +379,8 @@ namespace ts.server { } private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject) { - const { projectOptions } = this.convertConfigFileContentToProjectOptions(project.configFileName); + const { projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.configFileName); + this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors); const newRootFiles = projectOptions.files.map((f => this.getCanonicalFileName(f))); const currentRootFiles = project.getRootFiles().map((f => this.getCanonicalFileName(f))); @@ -410,6 +414,9 @@ namespace ts.server { return; } + const { configFileErrors } = this.convertConfigFileContentToProjectOptions(fileName); + this.reportConfigFileDiagnostics(fileName, configFileErrors); + this.logger.info(`Detected newly added tsconfig file: ${fileName}`); this.reloadProjects(); } @@ -657,38 +664,46 @@ namespace ts.server { private convertConfigFileContentToProjectOptions(configFilename: string): ConfigFileConversionResult { configFilename = normalizePath(configFilename); - const configObj = parseConfigFileTextToJson(configFilename, this.host.readFile(configFilename)); - if (configObj.error) { - return { success: false, configFileErrors: [configObj.error] }; + const configFileContent = this.host.readFile(configFilename); + let errors: Diagnostic[]; + + const result = parseConfigFileTextToJson(configFilename, configFileContent); + let config = result.config; + + if (result.error) { + // try to reparse config file + const { configJsonObject: sanitizedConfig, diagnostics } = sanitizeConfigFile(configFilename, configFileContent); + config = sanitizedConfig; + errors = diagnostics.length ? diagnostics : [result.error]; } const parsedCommandLine = parseJsonConfigFileContent( - configObj.config, + config, this.host, getDirectoryPath(configFilename), /*existingOptions*/ {}, configFilename); - Debug.assert(!!parsedCommandLine.fileNames); - - if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { - return { success: false, configFileErrors: parsedCommandLine.errors }; + if (parsedCommandLine.errors.length) { + errors = concatenate(errors, parsedCommandLine.errors); } + Debug.assert(!!parsedCommandLine.fileNames); + if (parsedCommandLine.fileNames.length === 0) { - const error = createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename); - return { success: false, configFileErrors: [error] }; + errors.push(createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + return { success: false, configFileErrors: errors }; } const projectOptions: ProjectOptions = { files: parsedCommandLine.fileNames, compilerOptions: parsedCommandLine.options, - configHasFilesProperty: configObj.config["files"] !== undefined, + configHasFilesProperty: config["files"] !== undefined, wildcardDirectories: createMap(parsedCommandLine.wildcardDirectories), typingOptions: parsedCommandLine.typingOptions, compileOnSave: parsedCommandLine.compileOnSave }; - return { success: true, projectOptions }; + return { success: true, projectOptions, configFileErrors: errors }; } private exceededTotalSizeLimitForNonTsFiles(options: CompilerOptions, fileNames: T[], propertyReader: FilePropertyReader) { @@ -718,12 +733,21 @@ namespace ts.server { /*languageServiceEnabled*/ !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, /*clientFileName*/ undefined, typingOptions); + this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, /*clientFileName*/ undefined, typingOptions, /*configFileErrors*/ undefined); this.externalProjects.push(project); return project; } - private createAndAddConfiguredProject(configFileName: NormalizedPath, projectOptions: ProjectOptions, clientFileName?: string) { + private reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile?: string) { + if (diagnostics && diagnostics.length > 0) { + this.eventHandler({ + eventName: "configFileDiag", + data: { configFileName, diagnostics, triggerFile } + }); + } + } + + private createAndAddConfiguredProject(configFileName: NormalizedPath, projectOptions: ProjectOptions, configFileErrors: Diagnostic[], clientFileName?: string) { const sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); const project = new ConfiguredProject( configFileName, @@ -735,7 +759,7 @@ namespace ts.server { /*languageServiceEnabled*/ !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions); + this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors); project.watchConfigFile(project => this.onConfigChangedForConfiguredProject(project)); if (!sizeLimitExceeded) { @@ -753,7 +777,7 @@ namespace ts.server { } } - private addFilesToProjectAndUpdateGraph(project: ConfiguredProject | ExternalProject, files: T[], propertyReader: FilePropertyReader, clientFileName: string, typingOptions: TypingOptions): void { + private addFilesToProjectAndUpdateGraph(project: ConfiguredProject | ExternalProject, files: T[], propertyReader: FilePropertyReader, clientFileName: string, typingOptions: TypingOptions, configFileErrors: Diagnostic[]): void { let errors: Diagnostic[]; for (const f of files) { const rootFilename = propertyReader.getFileName(f); @@ -767,21 +791,22 @@ namespace ts.server { (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename)); } } - project.setProjectErrors(errors); + project.setProjectErrors(concatenate(configFileErrors, errors)); project.setTypingOptions(typingOptions); project.updateGraph(); } private openConfigFile(configFileName: NormalizedPath, clientFileName?: string): OpenConfigFileResult { const conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); - if (!conversionResult.success) { - // open project with no files and set errors on the project - const project = this.createAndAddConfiguredProject(configFileName, { files: [], compilerOptions: {} }, clientFileName); - project.setProjectErrors(conversionResult.configFileErrors); - return { success: false, errors: conversionResult.configFileErrors }; - } - const project = this.createAndAddConfiguredProject(configFileName, conversionResult.projectOptions, clientFileName); - return { success: true, project, errors: project.getProjectErrors() }; + const projectOptions = conversionResult.success + ? conversionResult.projectOptions + : { files: [], compilerOptions: {} }; + const project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); + return { + success: conversionResult.success, + project, + errors: project.getProjectErrors() + }; } private updateNonInferredProject(project: ExternalProject | ConfiguredProject, newUncheckedFiles: T[], propertyReader: FilePropertyReader, newOptions: CompilerOptions, newTypingOptions: TypingOptions, compileOnSave: boolean, configFileErrors: Diagnostic[]) { diff --git a/src/server/session.ts b/src/server/session.ts index 1fdd75c037f..fb29ff40a10 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -164,18 +164,24 @@ namespace ts.server { protected readonly canUseEvents: boolean) { const eventHandler: ProjectServiceEventHandler = canUseEvents - ? (eventName, project, fileName) => this.handleEvent(eventName, project, fileName) + ? event => this.handleEvent(event) : undefined; this.projectService = new ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler); this.gcTimer = new GcTimer(host, /*delay*/ 15000, logger); } - private handleEvent(eventName: string, project: Project, fileName: NormalizedPath) { - if (eventName == "context") { - this.logger.info("got context event, updating diagnostics for" + fileName); - this.updateErrorCheck([{ fileName, project }], this.changeSeq, - (n) => n === this.changeSeq, 100); + private handleEvent(event: ProjectServiceEvent) { + switch (event.eventName) { + case "context": + const { project, fileName } = event.data; + this.projectService.logger.info(`got context event, updating diagnostics for ${fileName}`); + this.updateErrorCheck([{ fileName, project }], this.changeSeq, + (n) => n === this.changeSeq, 100); + break; + case "configFileDiag": + const { triggerFile, configFileName, diagnostics } = event.data; + this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); } } diff --git a/src/services/services.ts b/src/services/services.ts index 7fdb8edc248..39a447a3b74 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -296,11 +296,14 @@ namespace ts { let pos = this.pos; const useJSDocScanner = this.kind >= SyntaxKind.FirstJSDocTagNode && this.kind <= SyntaxKind.LastJSDocTagNode; const processNode = (node: Node) => { - if (pos < node.pos) { + const isJSDocTagNode = isJSDocTag(node); + if (!isJSDocTagNode && pos < node.pos) { pos = this.addSyntheticNodes(children, pos, node.pos, useJSDocScanner); } children.push(node); - pos = node.end; + if (!isJSDocTagNode) { + pos = node.end; + } }; const processNodes = (nodes: NodeArray) => { if (pos < nodes.pos) { @@ -7683,6 +7686,10 @@ namespace ts { * False will mean that node is not classified and traverse routine should recurse into node contents. */ function tryClassifyNode(node: Node): boolean { + if (isJSDocTag(node)) { + return true; + } + if (nodeIsMissing(node)) { return true; } diff --git a/src/services/shims.ts b/src/services/shims.ts index 1c4c6515444..3b2d9e68278 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -1188,6 +1188,6 @@ namespace TypeScript.Services { // TODO: it should be moved into a namespace though. /* @internal */ -const toolsVersion = "2.1"; +const toolsVersion = "2.0"; /* tslint:enable:no-unused-variable */ diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 7f41cdbb3a4..a14d6901a5a 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -925,4 +925,28 @@ namespace ts { } return ensureScriptKind(fileName, scriptKind); } + + export function sanitizeConfigFile(configFileName: string, content: string) { + const options: TranspileOptions = { + fileName: "config.js", + compilerOptions: { + target: ScriptTarget.ES6, + removeComments: true + }, + reportDiagnostics: true + }; + const { outputText, diagnostics } = ts.transpileModule("(" + content + ")", options); + // 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 + const trimmedOutput = outputText.trim(); + for (const diagnostic of diagnostics) { + diagnostic.start = diagnostic.start - 1; + } + const {config, error} = parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false); + return { + configJsonObject: config || {}, + diagnostics: error ? concatenate(diagnostics, [error]) : diagnostics + }; + } } \ No newline at end of file diff --git a/tests/baselines/reference/apparentTypeSubtyping.errors.txt b/tests/baselines/reference/apparentTypeSubtyping.errors.txt index e1a53ef6a73..01fffeb3824 100644 --- a/tests/baselines/reference/apparentTypeSubtyping.errors.txt +++ b/tests/baselines/reference/apparentTypeSubtyping.errors.txt @@ -1,6 +1,7 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtyping.ts(9,7): error TS2415: Class 'Derived' incorrectly extends base class 'Base'. Types of property 'x' are incompatible. Type 'String' is not assignable to type 'string'. + 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. ==== tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtyping.ts (1 errors) ==== @@ -17,6 +18,7 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSubtypi !!! error TS2415: Class 'Derived' incorrectly extends base class 'Base'. !!! error TS2415: Types of property 'x' are incompatible. !!! error TS2415: Type 'String' is not assignable to type 'string'. +!!! error TS2415: 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. x: String; } diff --git a/tests/baselines/reference/apparentTypeSupertype.errors.txt b/tests/baselines/reference/apparentTypeSupertype.errors.txt index 5fe5c92a5b3..c7610a80f2f 100644 --- a/tests/baselines/reference/apparentTypeSupertype.errors.txt +++ b/tests/baselines/reference/apparentTypeSupertype.errors.txt @@ -2,6 +2,7 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSuperty Types of property 'x' are incompatible. Type 'U' is not assignable to type 'string'. Type 'String' is not assignable to type 'string'. + 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. ==== tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSupertype.ts (1 errors) ==== @@ -19,5 +20,6 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSuperty !!! error TS2415: Types of property 'x' are incompatible. !!! error TS2415: Type 'U' is not assignable to type 'string'. !!! error TS2415: Type 'String' is not assignable to type 'string'. +!!! error TS2415: 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. x: U; } \ No newline at end of file diff --git a/tests/baselines/reference/arityAndOrderCompatibility01.errors.txt b/tests/baselines/reference/arityAndOrderCompatibility01.errors.txt index d60f0b7d03c..a6a685069d6 100644 --- a/tests/baselines/reference/arityAndOrderCompatibility01.errors.txt +++ b/tests/baselines/reference/arityAndOrderCompatibility01.errors.txt @@ -39,8 +39,7 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(26,5): error tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(27,5): error TS2322: Type '{ 0: string; 1: number; }' is not assignable to type '[string]'. Property 'length' is missing in type '{ 0: string; 1: number; }'. tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(28,5): error TS2322: Type '[string, number]' is not assignable to type '[number, string]'. - Types of property '0' are incompatible. - Type 'string' is not assignable to type 'number'. + Type 'string' is not assignable to type 'number'. tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(29,5): error TS2322: Type 'StrNum' is not assignable to type '[number, string]'. Types of property '0' are incompatible. Type 'string' is not assignable to type 'number'. @@ -136,8 +135,7 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(30,5): error var n1: [number, string] = x; ~~ !!! error TS2322: Type '[string, number]' is not assignable to type '[number, string]'. -!!! error TS2322: Types of property '0' are incompatible. -!!! error TS2322: Type 'string' is not assignable to type 'number'. +!!! error TS2322: Type 'string' is not assignable to type 'number'. var n2: [number, string] = y; ~~ !!! error TS2322: Type 'StrNum' is not assignable to type '[number, string]'. diff --git a/tests/baselines/reference/arrayLiterals3.errors.txt b/tests/baselines/reference/arrayLiterals3.errors.txt index 8e6c7eccf81..1f0dd30c09c 100644 --- a/tests/baselines/reference/arrayLiterals3.errors.txt +++ b/tests/baselines/reference/arrayLiterals3.errors.txt @@ -1,8 +1,7 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(10,5): error TS2322: Type 'undefined[]' is not assignable to type '[any, any, any]'. Property '0' is missing in type 'undefined[]'. tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(11,5): error TS2322: Type '[string, number, boolean]' is not assignable to type '[boolean, string, number]'. - Types of property '0' are incompatible. - Type 'string' is not assignable to type 'boolean'. + Type 'string' is not assignable to type 'boolean'. tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(17,5): error TS2322: Type '[number, number, string, boolean]' is not assignable to type '[number, number]'. Types of property 'pop' are incompatible. Type '() => string | number | boolean' is not assignable to type '() => number'. @@ -18,6 +17,7 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error Types of parameters 'items' and 'items' are incompatible. Type 'Number' is not assignable to type 'string | number'. Type 'Number' is not assignable to type 'number'. + 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible. ==== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts (6 errors) ==== @@ -37,8 +37,7 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error var a1: [boolean, string, number] = ["string", 1, true]; // Error ~~ !!! error TS2322: Type '[string, number, boolean]' is not assignable to type '[boolean, string, number]'. -!!! error TS2322: Types of property '0' are incompatible. -!!! error TS2322: Type 'string' is not assignable to type 'boolean'. +!!! error TS2322: Type 'string' is not assignable to type 'boolean'. // The resulting type an array literal expression is determined as follows: // - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1), @@ -81,4 +80,5 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error !!! error TS2322: Types of parameters 'items' and 'items' are incompatible. !!! error TS2322: Type 'Number' is not assignable to type 'string | number'. !!! error TS2322: Type 'Number' is not assignable to type 'number'. +!!! error TS2322: 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible. \ No newline at end of file diff --git a/tests/baselines/reference/assignFromBooleanInterface.errors.txt b/tests/baselines/reference/assignFromBooleanInterface.errors.txt index 4b06603a9bf..555b645cd7d 100644 --- a/tests/baselines/reference/assignFromBooleanInterface.errors.txt +++ b/tests/baselines/reference/assignFromBooleanInterface.errors.txt @@ -1,4 +1,5 @@ tests/cases/conformance/types/primitives/boolean/assignFromBooleanInterface.ts(3,1): error TS2322: Type 'Boolean' is not assignable to type 'boolean'. + 'boolean' is a primitive, but 'Boolean' is a wrapper object. Prefer using 'boolean' when possible. ==== tests/cases/conformance/types/primitives/boolean/assignFromBooleanInterface.ts (1 errors) ==== @@ -7,4 +8,5 @@ tests/cases/conformance/types/primitives/boolean/assignFromBooleanInterface.ts(3 x = a; ~ !!! error TS2322: Type 'Boolean' is not assignable to type 'boolean'. +!!! error TS2322: 'boolean' is a primitive, but 'Boolean' is a wrapper object. Prefer using 'boolean' when possible. a = x; \ No newline at end of file diff --git a/tests/baselines/reference/assignFromBooleanInterface2.errors.txt b/tests/baselines/reference/assignFromBooleanInterface2.errors.txt index c03eab60c74..6c7ebbe5ee8 100644 --- a/tests/baselines/reference/assignFromBooleanInterface2.errors.txt +++ b/tests/baselines/reference/assignFromBooleanInterface2.errors.txt @@ -3,6 +3,7 @@ tests/cases/conformance/types/primitives/boolean/assignFromBooleanInterface2.ts( Type '() => Object' is not assignable to type '() => boolean'. Type 'Object' is not assignable to type 'boolean'. tests/cases/conformance/types/primitives/boolean/assignFromBooleanInterface2.ts(19,1): error TS2322: Type 'Boolean' is not assignable to type 'boolean'. + 'boolean' is a primitive, but 'Boolean' is a wrapper object. Prefer using 'boolean' when possible. tests/cases/conformance/types/primitives/boolean/assignFromBooleanInterface2.ts(20,1): error TS2322: Type 'NotBoolean' is not assignable to type 'boolean'. @@ -33,6 +34,7 @@ tests/cases/conformance/types/primitives/boolean/assignFromBooleanInterface2.ts( x = a; // expected error ~ !!! error TS2322: Type 'Boolean' is not assignable to type 'boolean'. +!!! error TS2322: 'boolean' is a primitive, but 'Boolean' is a wrapper object. Prefer using 'boolean' when possible. x = b; // expected error ~ !!! error TS2322: Type 'NotBoolean' is not assignable to type 'boolean'. diff --git a/tests/baselines/reference/assignFromNumberInterface.errors.txt b/tests/baselines/reference/assignFromNumberInterface.errors.txt index 0c8c4a5f5ac..1a70ef342d2 100644 --- a/tests/baselines/reference/assignFromNumberInterface.errors.txt +++ b/tests/baselines/reference/assignFromNumberInterface.errors.txt @@ -1,4 +1,5 @@ tests/cases/conformance/types/primitives/number/assignFromNumberInterface.ts(3,1): error TS2322: Type 'Number' is not assignable to type 'number'. + 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible. ==== tests/cases/conformance/types/primitives/number/assignFromNumberInterface.ts (1 errors) ==== @@ -7,4 +8,5 @@ tests/cases/conformance/types/primitives/number/assignFromNumberInterface.ts(3,1 x = a; ~ !!! error TS2322: Type 'Number' is not assignable to type 'number'. +!!! error TS2322: 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible. a = x; \ No newline at end of file diff --git a/tests/baselines/reference/assignFromNumberInterface2.errors.txt b/tests/baselines/reference/assignFromNumberInterface2.errors.txt index 85639cdeeaf..3297501d612 100644 --- a/tests/baselines/reference/assignFromNumberInterface2.errors.txt +++ b/tests/baselines/reference/assignFromNumberInterface2.errors.txt @@ -1,4 +1,5 @@ tests/cases/conformance/types/primitives/number/assignFromNumberInterface2.ts(24,1): error TS2322: Type 'Number' is not assignable to type 'number'. + 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible. tests/cases/conformance/types/primitives/number/assignFromNumberInterface2.ts(25,1): error TS2322: Type 'NotNumber' is not assignable to type 'number'. @@ -29,6 +30,7 @@ tests/cases/conformance/types/primitives/number/assignFromNumberInterface2.ts(25 x = a; // expected error ~ !!! error TS2322: Type 'Number' is not assignable to type 'number'. +!!! error TS2322: 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible. x = b; // expected error ~ !!! error TS2322: Type 'NotNumber' is not assignable to type 'number'. diff --git a/tests/baselines/reference/assignFromStringInterface.errors.txt b/tests/baselines/reference/assignFromStringInterface.errors.txt index 6ec8afad120..7e7af4d1b9d 100644 --- a/tests/baselines/reference/assignFromStringInterface.errors.txt +++ b/tests/baselines/reference/assignFromStringInterface.errors.txt @@ -1,4 +1,5 @@ tests/cases/conformance/types/primitives/string/assignFromStringInterface.ts(3,1): error TS2322: Type 'String' is not assignable to type 'string'. + 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. ==== tests/cases/conformance/types/primitives/string/assignFromStringInterface.ts (1 errors) ==== @@ -7,4 +8,5 @@ tests/cases/conformance/types/primitives/string/assignFromStringInterface.ts(3,1 x = a; ~ !!! error TS2322: Type 'String' is not assignable to type 'string'. +!!! error TS2322: 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. a = x; \ No newline at end of file diff --git a/tests/baselines/reference/assignFromStringInterface2.errors.txt b/tests/baselines/reference/assignFromStringInterface2.errors.txt index 4e09eb6eacb..0fc3284bf00 100644 --- a/tests/baselines/reference/assignFromStringInterface2.errors.txt +++ b/tests/baselines/reference/assignFromStringInterface2.errors.txt @@ -1,4 +1,5 @@ tests/cases/conformance/types/primitives/string/assignFromStringInterface2.ts(47,1): error TS2322: Type 'String' is not assignable to type 'string'. + 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. tests/cases/conformance/types/primitives/string/assignFromStringInterface2.ts(48,1): error TS2322: Type 'NotString' is not assignable to type 'string'. @@ -52,6 +53,7 @@ tests/cases/conformance/types/primitives/string/assignFromStringInterface2.ts(48 x = a; // expected error ~ !!! error TS2322: Type 'String' is not assignable to type 'string'. +!!! error TS2322: 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. x = b; // expected error ~ !!! error TS2322: Type 'NotString' is not assignable to type 'string'. diff --git a/tests/baselines/reference/await_unaryExpression_es6.js b/tests/baselines/reference/await_unaryExpression_es6.js new file mode 100644 index 00000000000..46065bdada9 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es6.js @@ -0,0 +1,47 @@ +//// [await_unaryExpression_es6.ts] + +async function bar() { + !await 42; // OK +} + +async function bar1() { + +await 42; // OK +} + +async function bar3() { + -await 42; // OK +} + +async function bar4() { + ~await 42; // OK +} + +//// [await_unaryExpression_es6.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments)).next()); + }); +}; +function bar() { + return __awaiter(this, void 0, void 0, function* () { + !(yield 42); // OK + }); +} +function bar1() { + return __awaiter(this, void 0, void 0, function* () { + +(yield 42); // OK + }); +} +function bar3() { + return __awaiter(this, void 0, void 0, function* () { + -(yield 42); // OK + }); +} +function bar4() { + return __awaiter(this, void 0, void 0, function* () { + ~(yield 42); // OK + }); +} diff --git a/tests/baselines/reference/await_unaryExpression_es6.symbols b/tests/baselines/reference/await_unaryExpression_es6.symbols new file mode 100644 index 00000000000..81edd4b981b --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es6.symbols @@ -0,0 +1,25 @@ +=== tests/cases/conformance/async/es6/await_unaryExpression_es6.ts === + +async function bar() { +>bar : Symbol(bar, Decl(await_unaryExpression_es6.ts, 0, 0)) + + !await 42; // OK +} + +async function bar1() { +>bar1 : Symbol(bar1, Decl(await_unaryExpression_es6.ts, 3, 1)) + + +await 42; // OK +} + +async function bar3() { +>bar3 : Symbol(bar3, Decl(await_unaryExpression_es6.ts, 7, 1)) + + -await 42; // OK +} + +async function bar4() { +>bar4 : Symbol(bar4, Decl(await_unaryExpression_es6.ts, 11, 1)) + + ~await 42; // OK +} diff --git a/tests/baselines/reference/await_unaryExpression_es6.types b/tests/baselines/reference/await_unaryExpression_es6.types new file mode 100644 index 00000000000..2a4b7354d3e --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es6.types @@ -0,0 +1,37 @@ +=== tests/cases/conformance/async/es6/await_unaryExpression_es6.ts === + +async function bar() { +>bar : () => Promise + + !await 42; // OK +>!await 42 : boolean +>await 42 : number +>42 : number +} + +async function bar1() { +>bar1 : () => Promise + + +await 42; // OK +>+await 42 : number +>await 42 : number +>42 : number +} + +async function bar3() { +>bar3 : () => Promise + + -await 42; // OK +>-await 42 : number +>await 42 : number +>42 : number +} + +async function bar4() { +>bar4 : () => Promise + + ~await 42; // OK +>~await 42 : number +>await 42 : number +>42 : number +} diff --git a/tests/baselines/reference/await_unaryExpression_es6_1.js b/tests/baselines/reference/await_unaryExpression_es6_1.js new file mode 100644 index 00000000000..c6f5f1142c0 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es6_1.js @@ -0,0 +1,56 @@ +//// [await_unaryExpression_es6_1.ts] + +async function bar() { + !await 42; // OK +} + +async function bar1() { + delete await 42; // OK +} + +async function bar2() { + delete await 42; // OK +} + +async function bar3() { + void await 42; +} + +async function bar4() { + +await 42; +} + +//// [await_unaryExpression_es6_1.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments)).next()); + }); +}; +function bar() { + return __awaiter(this, void 0, void 0, function* () { + !(yield 42); // OK + }); +} +function bar1() { + return __awaiter(this, void 0, void 0, function* () { + delete (yield 42); // OK + }); +} +function bar2() { + return __awaiter(this, void 0, void 0, function* () { + delete (yield 42); // OK + }); +} +function bar3() { + return __awaiter(this, void 0, void 0, function* () { + void (yield 42); + }); +} +function bar4() { + return __awaiter(this, void 0, void 0, function* () { + +(yield 42); + }); +} diff --git a/tests/baselines/reference/await_unaryExpression_es6_1.symbols b/tests/baselines/reference/await_unaryExpression_es6_1.symbols new file mode 100644 index 00000000000..ed7d7e4ed02 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es6_1.symbols @@ -0,0 +1,31 @@ +=== tests/cases/conformance/async/es6/await_unaryExpression_es6_1.ts === + +async function bar() { +>bar : Symbol(bar, Decl(await_unaryExpression_es6_1.ts, 0, 0)) + + !await 42; // OK +} + +async function bar1() { +>bar1 : Symbol(bar1, Decl(await_unaryExpression_es6_1.ts, 3, 1)) + + delete await 42; // OK +} + +async function bar2() { +>bar2 : Symbol(bar2, Decl(await_unaryExpression_es6_1.ts, 7, 1)) + + delete await 42; // OK +} + +async function bar3() { +>bar3 : Symbol(bar3, Decl(await_unaryExpression_es6_1.ts, 11, 1)) + + void await 42; +} + +async function bar4() { +>bar4 : Symbol(bar4, Decl(await_unaryExpression_es6_1.ts, 15, 1)) + + +await 42; +} diff --git a/tests/baselines/reference/await_unaryExpression_es6_1.types b/tests/baselines/reference/await_unaryExpression_es6_1.types new file mode 100644 index 00000000000..a5c3740b677 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es6_1.types @@ -0,0 +1,46 @@ +=== tests/cases/conformance/async/es6/await_unaryExpression_es6_1.ts === + +async function bar() { +>bar : () => Promise + + !await 42; // OK +>!await 42 : boolean +>await 42 : number +>42 : number +} + +async function bar1() { +>bar1 : () => Promise + + delete await 42; // OK +>delete await 42 : boolean +>await 42 : number +>42 : number +} + +async function bar2() { +>bar2 : () => Promise + + delete await 42; // OK +>delete await 42 : boolean +>await 42 : number +>42 : number +} + +async function bar3() { +>bar3 : () => Promise + + void await 42; +>void await 42 : undefined +>await 42 : number +>42 : number +} + +async function bar4() { +>bar4 : () => Promise + + +await 42; +>+await 42 : number +>await 42 : number +>42 : number +} diff --git a/tests/baselines/reference/await_unaryExpression_es6_2.js b/tests/baselines/reference/await_unaryExpression_es6_2.js new file mode 100644 index 00000000000..3c341018ed1 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es6_2.js @@ -0,0 +1,38 @@ +//// [await_unaryExpression_es6_2.ts] + +async function bar1() { + delete await 42; +} + +async function bar2() { + delete await 42; +} + +async function bar3() { + void await 42; +} + +//// [await_unaryExpression_es6_2.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments)).next()); + }); +}; +function bar1() { + return __awaiter(this, void 0, void 0, function* () { + delete (yield 42); + }); +} +function bar2() { + return __awaiter(this, void 0, void 0, function* () { + delete (yield 42); + }); +} +function bar3() { + return __awaiter(this, void 0, void 0, function* () { + void (yield 42); + }); +} diff --git a/tests/baselines/reference/await_unaryExpression_es6_2.symbols b/tests/baselines/reference/await_unaryExpression_es6_2.symbols new file mode 100644 index 00000000000..574ea4d433a --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es6_2.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/async/es6/await_unaryExpression_es6_2.ts === + +async function bar1() { +>bar1 : Symbol(bar1, Decl(await_unaryExpression_es6_2.ts, 0, 0)) + + delete await 42; +} + +async function bar2() { +>bar2 : Symbol(bar2, Decl(await_unaryExpression_es6_2.ts, 3, 1)) + + delete await 42; +} + +async function bar3() { +>bar3 : Symbol(bar3, Decl(await_unaryExpression_es6_2.ts, 7, 1)) + + void await 42; +} diff --git a/tests/baselines/reference/await_unaryExpression_es6_2.types b/tests/baselines/reference/await_unaryExpression_es6_2.types new file mode 100644 index 00000000000..b438f063add --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es6_2.types @@ -0,0 +1,28 @@ +=== tests/cases/conformance/async/es6/await_unaryExpression_es6_2.ts === + +async function bar1() { +>bar1 : () => Promise + + delete await 42; +>delete await 42 : boolean +>await 42 : number +>42 : number +} + +async function bar2() { +>bar2 : () => Promise + + delete await 42; +>delete await 42 : boolean +>await 42 : number +>42 : number +} + +async function bar3() { +>bar3 : () => Promise + + void await 42; +>void await 42 : undefined +>await 42 : number +>42 : number +} diff --git a/tests/baselines/reference/await_unaryExpression_es6_3.errors.txt b/tests/baselines/reference/await_unaryExpression_es6_3.errors.txt new file mode 100644 index 00000000000..5518f84983f --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es6_3.errors.txt @@ -0,0 +1,27 @@ +tests/cases/conformance/async/es6/await_unaryExpression_es6_3.ts(3,7): error TS1109: Expression expected. +tests/cases/conformance/async/es6/await_unaryExpression_es6_3.ts(7,7): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es6/await_unaryExpression_es6_3.ts (2 errors) ==== + + async function bar1() { + ++await 42; // Error + ~~~~~ +!!! error TS1109: Expression expected. + } + + async function bar2() { + --await 42; // Error + ~~~~~ +!!! error TS1109: Expression expected. + } + + async function bar3() { + var x = 42; + await x++; // OK but shouldn't need parenthesis + } + + async function bar4() { + var x = 42; + await x--; // OK but shouldn't need parenthesis + } \ No newline at end of file diff --git a/tests/baselines/reference/await_unaryExpression_es6_3.js b/tests/baselines/reference/await_unaryExpression_es6_3.js new file mode 100644 index 00000000000..077e264c450 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es6_3.js @@ -0,0 +1,53 @@ +//// [await_unaryExpression_es6_3.ts] + +async function bar1() { + ++await 42; // Error +} + +async function bar2() { + --await 42; // Error +} + +async function bar3() { + var x = 42; + await x++; // OK but shouldn't need parenthesis +} + +async function bar4() { + var x = 42; + await x--; // OK but shouldn't need parenthesis +} + +//// [await_unaryExpression_es6_3.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments)).next()); + }); +}; +function bar1() { + return __awaiter(this, void 0, void 0, function* () { + ++; + yield 42; // Error + }); +} +function bar2() { + return __awaiter(this, void 0, void 0, function* () { + --; + yield 42; // Error + }); +} +function bar3() { + return __awaiter(this, void 0, void 0, function* () { + var x = 42; + yield x++; // OK but shouldn't need parenthesis + }); +} +function bar4() { + return __awaiter(this, void 0, void 0, function* () { + var x = 42; + yield x--; // OK but shouldn't need parenthesis + }); +} diff --git a/tests/baselines/reference/castOfAwait.js b/tests/baselines/reference/castOfAwait.js index 95817b7f0e6..26e9812bf43 100644 --- a/tests/baselines/reference/castOfAwait.js +++ b/tests/baselines/reference/castOfAwait.js @@ -20,9 +20,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function f() { return __awaiter(this, void 0, void 0, function* () { yield 0; - typeof yield 0; - void yield 0; - yield void typeof void yield 0; + typeof (yield 0); + void (yield 0); + yield void typeof void (yield 0); yield yield 0; }); } diff --git a/tests/baselines/reference/castingTuple.errors.txt b/tests/baselines/reference/castingTuple.errors.txt index 6d5549c6bf2..2f9eeedf9ef 100644 --- a/tests/baselines/reference/castingTuple.errors.txt +++ b/tests/baselines/reference/castingTuple.errors.txt @@ -1,10 +1,8 @@ tests/cases/conformance/types/tuple/castingTuple.ts(28,10): error TS2352: Type '[number, string]' cannot be converted to type '[number, number]'. - Types of property '1' are incompatible. - Type 'string' is not comparable to type 'number'. + Type 'string' is not comparable to type 'number'. tests/cases/conformance/types/tuple/castingTuple.ts(29,10): error TS2352: Type '[C, D]' cannot be converted to type '[A, I]'. - Types of property '0' are incompatible. - Type 'C' is not comparable to type 'A'. - Property 'a' is missing in type 'C'. + Type 'C' is not comparable to type 'A'. + Property 'a' is missing in type 'C'. tests/cases/conformance/types/tuple/castingTuple.ts(30,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'array1' must be of type '{}[]', but here has type 'number[]'. tests/cases/conformance/types/tuple/castingTuple.ts(31,1): error TS2304: Cannot find name 't4'. @@ -40,14 +38,12 @@ tests/cases/conformance/types/tuple/castingTuple.ts(31,1): error TS2304: Cannot var t3 = <[number, number]>numStrTuple; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2352: Type '[number, string]' cannot be converted to type '[number, number]'. -!!! error TS2352: Types of property '1' are incompatible. -!!! error TS2352: Type 'string' is not comparable to type 'number'. +!!! error TS2352: Type 'string' is not comparable to type 'number'. var t9 = <[A, I]>classCDTuple; ~~~~~~~~~~~~~~~~~~~~ !!! error TS2352: Type '[C, D]' cannot be converted to type '[A, I]'. -!!! error TS2352: Types of property '0' are incompatible. -!!! error TS2352: Type 'C' is not comparable to type 'A'. -!!! error TS2352: Property 'a' is missing in type 'C'. +!!! error TS2352: Type 'C' is not comparable to type 'A'. +!!! error TS2352: Property 'a' is missing in type 'C'. var array1 = numStrTuple; ~~~~~~ !!! error TS2403: Subsequent variable declarations must have the same type. Variable 'array1' must be of type '{}[]', but here has type 'number[]'. diff --git a/tests/baselines/reference/contextualTypeWithTuple.errors.txt b/tests/baselines/reference/contextualTypeWithTuple.errors.txt index e0580ca2379..a488d8c7648 100644 --- a/tests/baselines/reference/contextualTypeWithTuple.errors.txt +++ b/tests/baselines/reference/contextualTypeWithTuple.errors.txt @@ -5,9 +5,8 @@ tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(3,5): error TS232 Type 'true' is not assignable to type 'string | number'. tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(15,1): error TS2322: Type '[number, string, boolean]' is not assignable to type '[number, string]'. tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(18,1): error TS2322: Type '[{}, number]' is not assignable to type '[{ a: string; }, number]'. - Types of property '0' are incompatible. - Type '{}' is not assignable to type '{ a: string; }'. - Property 'a' is missing in type '{}'. + Type '{}' is not assignable to type '{ a: string; }'. + Property 'a' is missing in type '{}'. tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(19,1): error TS2322: Type '[number, string]' is not assignable to type '[number, string, boolean]'. Property '2' is missing in type '[number, string]'. tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(20,5): error TS2322: Type '[string, string, number]' is not assignable to type '[string, string]'. @@ -18,9 +17,8 @@ tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(20,5): error TS23 tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(24,1): error TS2322: Type '[C, string | number]' is not assignable to type '[C, string | number, D]'. Property '2' is missing in type '[C, string | number]'. tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(25,1): error TS2322: Type '[number, string | number]' is not assignable to type '[number, string]'. - Types of property '1' are incompatible. - Type 'string | number' is not assignable to type 'string'. - Type 'number' is not assignable to type 'string'. + Type 'string | number' is not assignable to type 'string'. + Type 'number' is not assignable to type 'string'. ==== tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts (7 errors) ==== @@ -52,9 +50,8 @@ tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(25,1): error TS23 objNumTuple = [ {}, 5]; ~~~~~~~~~~~ !!! error TS2322: Type '[{}, number]' is not assignable to type '[{ a: string; }, number]'. -!!! error TS2322: Types of property '0' are incompatible. -!!! error TS2322: Type '{}' is not assignable to type '{ a: string; }'. -!!! error TS2322: Property 'a' is missing in type '{}'. +!!! error TS2322: Type '{}' is not assignable to type '{ a: string; }'. +!!! error TS2322: Property 'a' is missing in type '{}'. numStrBoolTuple = numStrTuple; ~~~~~~~~~~~~~~~ !!! error TS2322: Type '[number, string]' is not assignable to type '[number, string, boolean]'. @@ -76,6 +73,5 @@ tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(25,1): error TS23 numStrTuple = unionTuple3; ~~~~~~~~~~~ !!! error TS2322: Type '[number, string | number]' is not assignable to type '[number, string]'. -!!! error TS2322: Types of property '1' are incompatible. -!!! error TS2322: Type 'string | number' is not assignable to type 'string'. -!!! error TS2322: Type 'number' is not assignable to type 'string'. \ No newline at end of file +!!! error TS2322: Type 'string | number' is not assignable to type 'string'. +!!! error TS2322: Type 'number' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.errors.txt b/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.errors.txt index 42d617887e0..447ccec5ddf 100644 --- a/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.errors.txt +++ b/tests/baselines/reference/contextuallyTypedBindingInitializerNegative.errors.txt @@ -11,8 +11,7 @@ tests/cases/conformance/types/contextualTypes/methodDeclarations/contextuallyTyp tests/cases/conformance/types/contextualTypes/methodDeclarations/contextuallyTypedBindingInitializerNegative.ts(16,23): error TS2322: Type '(arg: string) => number' is not assignable to type '(s: string) => string'. Type 'number' is not assignable to type 'string'. tests/cases/conformance/types/contextualTypes/methodDeclarations/contextuallyTypedBindingInitializerNegative.ts(21,14): error TS2322: Type '[number, number]' is not assignable to type '[string, number]'. - Types of property '0' are incompatible. - Type 'number' is not assignable to type 'string'. + Type 'number' is not assignable to type 'string'. tests/cases/conformance/types/contextualTypes/methodDeclarations/contextuallyTypedBindingInitializerNegative.ts(26,14): error TS2322: Type '"baz"' is not assignable to type '"foo" | "bar"'. @@ -57,8 +56,7 @@ tests/cases/conformance/types/contextualTypes/methodDeclarations/contextuallyTyp function g({ prop = [101, 1234] }: Tuples) {} ~~~~ !!! error TS2322: Type '[number, number]' is not assignable to type '[string, number]'. -!!! error TS2322: Types of property '0' are incompatible. -!!! error TS2322: Type 'number' is not assignable to type 'string'. +!!! error TS2322: Type 'number' is not assignable to type 'string'. interface StringUnion { prop: "foo" | "bar"; diff --git a/tests/baselines/reference/declFileConstructors.js b/tests/baselines/reference/declFileConstructors.js index 8e92b1a36ae..44e816712fb 100644 --- a/tests/baselines/reference/declFileConstructors.js +++ b/tests/baselines/reference/declFileConstructors.js @@ -247,7 +247,7 @@ export declare class ConstructorWithPrivateParameterProperty { constructor(x: string); } export declare class ConstructorWithOptionalParameterProperty { - x?: string; + x: string; constructor(x?: string); } export declare class ConstructorWithParameterInitializer { @@ -281,7 +281,7 @@ declare class GlobalConstructorWithPrivateParameterProperty { constructor(x: string); } declare class GlobalConstructorWithOptionalParameterProperty { - x?: string; + x: string; constructor(x?: string); } declare class GlobalConstructorWithParameterInitializer { diff --git a/tests/baselines/reference/declarationsAndAssignments.errors.txt b/tests/baselines/reference/declarationsAndAssignments.errors.txt index 517eaafe4ab..3ed9e241c39 100644 --- a/tests/baselines/reference/declarationsAndAssignments.errors.txt +++ b/tests/baselines/reference/declarationsAndAssignments.errors.txt @@ -18,11 +18,9 @@ tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(73,14): tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(74,11): error TS2459: Type 'undefined[]' has no property 'a' and no string index signature. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(74,14): error TS2459: Type 'undefined[]' has no property 'b' and no string index signature. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(106,5): error TS2345: Argument of type '[number, [string, { y: boolean; }]]' is not assignable to parameter of type '[number, [string, { x: any; y?: boolean; }]]'. - Types of property '1' are incompatible. - Type '[string, { y: boolean; }]' is not assignable to type '[string, { x: any; y?: boolean; }]'. - Types of property '1' are incompatible. - Type '{ y: boolean; }' is not assignable to type '{ x: any; y?: boolean; }'. - Property 'x' is missing in type '{ y: boolean; }'. + Type '[string, { y: boolean; }]' is not assignable to type '[string, { x: any; y?: boolean; }]'. + Type '{ y: boolean; }' is not assignable to type '{ x: any; y?: boolean; }'. + Property 'x' is missing in type '{ y: boolean; }'. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(138,6): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(138,9): error TS2322: Type 'number' is not assignable to type 'string'. @@ -174,11 +172,9 @@ tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(138,9): f14([2, ["abc", { y: false }]]); // Error, no x ~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '[number, [string, { y: boolean; }]]' is not assignable to parameter of type '[number, [string, { x: any; y?: boolean; }]]'. -!!! error TS2345: Types of property '1' are incompatible. -!!! error TS2345: Type '[string, { y: boolean; }]' is not assignable to type '[string, { x: any; y?: boolean; }]'. -!!! error TS2345: Types of property '1' are incompatible. -!!! error TS2345: Type '{ y: boolean; }' is not assignable to type '{ x: any; y?: boolean; }'. -!!! error TS2345: Property 'x' is missing in type '{ y: boolean; }'. +!!! error TS2345: Type '[string, { y: boolean; }]' is not assignable to type '[string, { x: any; y?: boolean; }]'. +!!! error TS2345: Type '{ y: boolean; }' is not assignable to type '{ x: any; y?: boolean; }'. +!!! error TS2345: Property 'x' is missing in type '{ y: boolean; }'. module M { export var [a, b] = [1, 2]; diff --git a/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment2.errors.txt b/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment2.errors.txt index 3348effe822..e22b23122d3 100644 --- a/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment2.errors.txt +++ b/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment2.errors.txt @@ -2,8 +2,7 @@ tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAss tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment2.ts(3,12): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment2.ts(4,5): error TS2461: Type 'undefined' is not an array type. tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment2.ts(9,5): error TS2322: Type '[number, number, string]' is not assignable to type '[number, boolean, string]'. - Types of property '1' are incompatible. - Type 'number' is not assignable to type 'boolean'. + Type 'number' is not assignable to type 'boolean'. tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment2.ts(17,6): error TS2322: Type 'string' is not assignable to type 'Number'. tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAssignment2.ts(22,5): error TS2322: Type 'number[]' is not assignable to type '[number, number]'. Property '0' is missing in type 'number[]'. @@ -30,8 +29,7 @@ tests/cases/conformance/es6/destructuring/destructuringArrayBindingPatternAndAss var [b0, b1, b2]: [number, boolean, string] = [1, 2, "string"]; // Error ~~~~~~~~~~~~ !!! error TS2322: Type '[number, number, string]' is not assignable to type '[number, boolean, string]'. -!!! error TS2322: Types of property '1' are incompatible. -!!! error TS2322: Type 'number' is not assignable to type 'boolean'. +!!! error TS2322: Type 'number' is not assignable to type 'boolean'. interface J extends Array { 2: number; } diff --git a/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt b/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt index 878bb38abf0..d76a4efe5f1 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt +++ b/tests/baselines/reference/destructuringParameterDeclaration2.errors.txt @@ -1,6 +1,5 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts(7,4): error TS2345: Argument of type '[number, string, string[][]]' is not assignable to parameter of type '[number, number, string[][]]'. - Types of property '1' are incompatible. - Type 'string' is not assignable to type 'number'. + Type 'string' is not assignable to type 'number'. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts(7,29): error TS1005: ',' expected. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts(8,4): error TS2345: Argument of type '[number, number, string[][], string]' is not assignable to parameter of type '[number, number, string[][]]'. Types of property 'pop' are incompatible. @@ -32,12 +31,9 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts( Types of property '2' are incompatible. Type 'boolean' is not assignable to type '[[any]]'. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts(40,4): error TS2345: Argument of type '[number, number, [[string]]]' is not assignable to parameter of type '[any, any, [[number]]]'. - Types of property '2' are incompatible. - Type '[[string]]' is not assignable to type '[[number]]'. - Types of property '0' are incompatible. - Type '[string]' is not assignable to type '[number]'. - Types of property '0' are incompatible. - Type 'string' is not assignable to type 'number'. + Type '[[string]]' is not assignable to type '[[number]]'. + Type '[string]' is not assignable to type '[number]'. + Type 'string' is not assignable to type 'number'. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts(46,13): error TS2463: A binding pattern parameter cannot be optional in an implementation signature. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts(47,13): error TS2463: A binding pattern parameter cannot be optional in an implementation signature. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts(55,7): error TS2420: Class 'C4' incorrectly implements interface 'F2'. @@ -62,8 +58,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts( a0([1, "string", [["world"]]); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '[number, string, string[][]]' is not assignable to parameter of type '[number, number, string[][]]'. -!!! error TS2345: Types of property '1' are incompatible. -!!! error TS2345: Type 'string' is not assignable to type 'number'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. ~ !!! error TS1005: ',' expected. a0([1, 2, [["world"]], "string"]); // Error @@ -142,12 +137,9 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration2.ts( c6([1, 2, [["string"]]]); // Error, implied type is [any, any, [[number]]] // Use initializer ~~~~~~~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '[number, number, [[string]]]' is not assignable to parameter of type '[any, any, [[number]]]'. -!!! error TS2345: Types of property '2' are incompatible. -!!! error TS2345: Type '[[string]]' is not assignable to type '[[number]]'. -!!! error TS2345: Types of property '0' are incompatible. -!!! error TS2345: Type '[string]' is not assignable to type '[number]'. -!!! error TS2345: Types of property '0' are incompatible. -!!! error TS2345: Type 'string' is not assignable to type 'number'. +!!! error TS2345: Type '[[string]]' is not assignable to type '[[number]]'. +!!! error TS2345: Type '[string]' is not assignable to type '[number]'. +!!! error TS2345: Type 'string' is not assignable to type 'number'. // A parameter can be marked optional by following its name or binding pattern with a question mark (?) // or by including an initializer. Initializers (including binding property or element initializers) are diff --git a/tests/baselines/reference/destructuringParameterProperties2.errors.txt b/tests/baselines/reference/destructuringParameterProperties2.errors.txt index ec0f400631f..deb039aa67d 100644 --- a/tests/baselines/reference/destructuringParameterProperties2.errors.txt +++ b/tests/baselines/reference/destructuringParameterProperties2.errors.txt @@ -6,8 +6,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts(9 tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts(13,21): error TS2339: Property 'b' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts(17,21): error TS2339: Property 'c' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts(21,27): error TS2345: Argument of type '[number, undefined, string]' is not assignable to parameter of type '[number, string, boolean]'. - Types of property '2' are incompatible. - Type 'string' is not assignable to type 'boolean'. + Type 'string' is not assignable to type 'boolean'. ==== tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts (8 errors) ==== @@ -48,8 +47,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts(2 var x = new C1(undefined, [0, undefined, ""]); ~~~~~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '[number, undefined, string]' is not assignable to parameter of type '[number, string, boolean]'. -!!! error TS2345: Types of property '2' are incompatible. -!!! error TS2345: Type 'string' is not assignable to type 'boolean'. +!!! error TS2345: Type 'string' is not assignable to type 'boolean'. var [x_a, x_b, x_c] = [x.getA(), x.getB(), x.getC()]; var y = new C1(10, [0, "", true]); diff --git a/tests/baselines/reference/destructuringParameterProperties5.errors.txt b/tests/baselines/reference/destructuringParameterProperties5.errors.txt index 6f5801b7898..8eff6ad0feb 100644 --- a/tests/baselines/reference/destructuringParameterProperties5.errors.txt +++ b/tests/baselines/reference/destructuringParameterProperties5.errors.txt @@ -8,9 +8,8 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(7 tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(7,62): error TS2339: Property 'y' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(7,72): error TS2339: Property 'z' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(11,19): error TS2345: Argument of type '[{ x1: number; x2: string; x3: boolean; }, string, boolean]' is not assignable to parameter of type '[{ x: number; y: string; z: boolean; }, number, string]'. - Types of property '0' are incompatible. - Type '{ x1: number; x2: string; x3: boolean; }' is not assignable to type '{ x: number; y: string; z: boolean; }'. - Object literal may only specify known properties, and 'x1' does not exist in type '{ x: number; y: string; z: boolean; }'. + Type '{ x1: number; x2: string; x3: boolean; }' is not assignable to type '{ x: number; y: string; z: boolean; }'. + Object literal may only specify known properties, and 'x1' does not exist in type '{ x: number; y: string; z: boolean; }'. ==== tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts (10 errors) ==== @@ -45,7 +44,6 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(1 var a = new C1([{ x1: 10, x2: "", x3: true }, "", false]); ~~~~~~ !!! error TS2345: Argument of type '[{ x1: number; x2: string; x3: boolean; }, string, boolean]' is not assignable to parameter of type '[{ x: number; y: string; z: boolean; }, number, string]'. -!!! error TS2345: Types of property '0' are incompatible. -!!! error TS2345: Type '{ x1: number; x2: string; x3: boolean; }' is not assignable to type '{ x: number; y: string; z: boolean; }'. -!!! error TS2345: Object literal may only specify known properties, and 'x1' does not exist in type '{ x: number; y: string; z: boolean; }'. +!!! error TS2345: Type '{ x1: number; x2: string; x3: boolean; }' is not assignable to type '{ x: number; y: string; z: boolean; }'. +!!! error TS2345: Object literal may only specify known properties, and 'x1' does not exist in type '{ x: number; y: string; z: boolean; }'. var [a_x1, a_x2, a_x3, a_y, a_z] = [a.x1, a.x2, a.x3, a.y, a.z]; \ No newline at end of file diff --git a/tests/baselines/reference/destructuringVariableDeclaration2.errors.txt b/tests/baselines/reference/destructuringVariableDeclaration2.errors.txt index 1a655837743..bdbda6f9a96 100644 --- a/tests/baselines/reference/destructuringVariableDeclaration2.errors.txt +++ b/tests/baselines/reference/destructuringVariableDeclaration2.errors.txt @@ -2,12 +2,9 @@ tests/cases/conformance/es6/destructuring/destructuringVariableDeclaration2.ts(3 Types of property 'a1' are incompatible. Type 'boolean' is not assignable to type 'number'. tests/cases/conformance/es6/destructuring/destructuringVariableDeclaration2.ts(4,5): error TS2322: Type '[number, [[boolean]], boolean]' is not assignable to type '[number, [[string]], boolean]'. - Types of property '1' are incompatible. - Type '[[boolean]]' is not assignable to type '[[string]]'. - Types of property '0' are incompatible. - Type '[boolean]' is not assignable to type '[string]'. - Types of property '0' are incompatible. - Type 'boolean' is not assignable to type 'string'. + Type '[[boolean]]' is not assignable to type '[[string]]'. + Type '[boolean]' is not assignable to type '[string]'. + Type 'boolean' is not assignable to type 'string'. tests/cases/conformance/es6/destructuring/destructuringVariableDeclaration2.ts(9,25): error TS2322: Type '{ t1: boolean; t2: string; }' is not assignable to type '{ t1: boolean; t2: number; }'. Types of property 't2' are incompatible. Type 'string' is not assignable to type 'number'. @@ -28,12 +25,9 @@ tests/cases/conformance/es6/destructuring/destructuringVariableDeclaration2.ts(1 var [a3, [[a4]], a5]: [number, [[string]], boolean] = [1, [[false]], true]; // Error ~~~~~~~~~~~~~~~~ !!! error TS2322: Type '[number, [[boolean]], boolean]' is not assignable to type '[number, [[string]], boolean]'. -!!! error TS2322: Types of property '1' are incompatible. -!!! error TS2322: Type '[[boolean]]' is not assignable to type '[[string]]'. -!!! error TS2322: Types of property '0' are incompatible. -!!! error TS2322: Type '[boolean]' is not assignable to type '[string]'. -!!! error TS2322: Types of property '0' are incompatible. -!!! error TS2322: Type 'boolean' is not assignable to type 'string'. +!!! error TS2322: Type '[[boolean]]' is not assignable to type '[[string]]'. +!!! error TS2322: Type '[boolean]' is not assignable to type '[string]'. +!!! error TS2322: Type 'boolean' is not assignable to type 'string'. // The type T associated with a destructuring variable declaration is determined as follows: // Otherwise, if the declaration includes an initializer expression, T is the type of that initializer expression. diff --git a/tests/baselines/reference/errorForConflictingExportEqualsValue.errors.txt b/tests/baselines/reference/errorForConflictingExportEqualsValue.errors.txt new file mode 100644 index 00000000000..9a5858f46ab --- /dev/null +++ b/tests/baselines/reference/errorForConflictingExportEqualsValue.errors.txt @@ -0,0 +1,9 @@ +tests/cases/compiler/errorForConflictingExportEqualsValue.ts(2,1): error TS2309: An export assignment cannot be used in a module with other exported elements. + + +==== tests/cases/compiler/errorForConflictingExportEqualsValue.ts (1 errors) ==== + export var x; + export = {}; + ~~~~~~~~~~~~ +!!! error TS2309: An export assignment cannot be used in a module with other exported elements. + \ No newline at end of file diff --git a/tests/baselines/reference/errorForConflictingExportEqualsValue.js b/tests/baselines/reference/errorForConflictingExportEqualsValue.js new file mode 100644 index 00000000000..88762e7e846 --- /dev/null +++ b/tests/baselines/reference/errorForConflictingExportEqualsValue.js @@ -0,0 +1,8 @@ +//// [errorForConflictingExportEqualsValue.ts] +export var x; +export = {}; + + +//// [errorForConflictingExportEqualsValue.js] +"use strict"; +module.exports = {}; diff --git a/tests/baselines/reference/genericCallWithTupleType.errors.txt b/tests/baselines/reference/genericCallWithTupleType.errors.txt index 0194dc61311..617c4f7159b 100644 --- a/tests/baselines/reference/genericCallWithTupleType.errors.txt +++ b/tests/baselines/reference/genericCallWithTupleType.errors.txt @@ -6,11 +6,9 @@ tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTup tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(14,1): error TS2322: Type '{ a: string; }' is not assignable to type 'string | number'. Type '{ a: string; }' is not assignable to type 'number'. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(22,1): error TS2322: Type '[number, string]' is not assignable to type '[string, number]'. - Types of property '0' are incompatible. - Type 'number' is not assignable to type 'string'. + Type 'number' is not assignable to type 'string'. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(23,1): error TS2322: Type '[{}, {}]' is not assignable to type '[string, number]'. - Types of property '0' are incompatible. - Type '{}' is not assignable to type 'string'. + Type '{}' is not assignable to type 'string'. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(24,1): error TS2322: Type '[{}]' is not assignable to type '[{}, {}]'. Property '1' is missing in type '[{}]'. @@ -49,13 +47,11 @@ tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTup i1.tuple1 = [5, "foo"]; ~~~~~~~~~ !!! error TS2322: Type '[number, string]' is not assignable to type '[string, number]'. -!!! error TS2322: Types of property '0' are incompatible. -!!! error TS2322: Type 'number' is not assignable to type 'string'. +!!! error TS2322: Type 'number' is not assignable to type 'string'. i1.tuple1 = [{}, {}]; ~~~~~~~~~ !!! error TS2322: Type '[{}, {}]' is not assignable to type '[string, number]'. -!!! error TS2322: Types of property '0' are incompatible. -!!! error TS2322: Type '{}' is not assignable to type 'string'. +!!! error TS2322: Type '{}' is not assignable to type 'string'. i2.tuple1 = [{}]; ~~~~~~~~~ !!! error TS2322: Type '[{}]' is not assignable to type '[{}, {}]'. diff --git a/tests/baselines/reference/instantiateContextuallyTypedGenericThis.js b/tests/baselines/reference/instantiateContextuallyTypedGenericThis.js new file mode 100644 index 00000000000..176df15985f --- /dev/null +++ b/tests/baselines/reference/instantiateContextuallyTypedGenericThis.js @@ -0,0 +1,20 @@ +//// [instantiateContextuallyTypedGenericThis.ts] +interface JQuery { + each( + collection: T[], callback: (this: T, dit: T) => T + ): T[]; +} + +let $: JQuery; +let lines: string[]; +$.each(lines, function(dit) { + return dit.charAt(0) + this.charAt(1); +}); + + +//// [instantiateContextuallyTypedGenericThis.js] +var $; +var lines; +$.each(lines, function (dit) { + return dit.charAt(0) + this.charAt(1); +}); diff --git a/tests/baselines/reference/instantiateContextuallyTypedGenericThis.symbols b/tests/baselines/reference/instantiateContextuallyTypedGenericThis.symbols new file mode 100644 index 00000000000..1db5b30dd0b --- /dev/null +++ b/tests/baselines/reference/instantiateContextuallyTypedGenericThis.symbols @@ -0,0 +1,46 @@ +=== tests/cases/compiler/instantiateContextuallyTypedGenericThis.ts === +interface JQuery { +>JQuery : Symbol(JQuery, Decl(instantiateContextuallyTypedGenericThis.ts, 0, 0)) + + each( +>each : Symbol(JQuery.each, Decl(instantiateContextuallyTypedGenericThis.ts, 0, 18)) +>T : Symbol(T, Decl(instantiateContextuallyTypedGenericThis.ts, 1, 9)) + + collection: T[], callback: (this: T, dit: T) => T +>collection : Symbol(collection, Decl(instantiateContextuallyTypedGenericThis.ts, 1, 12)) +>T : Symbol(T, Decl(instantiateContextuallyTypedGenericThis.ts, 1, 9)) +>callback : Symbol(callback, Decl(instantiateContextuallyTypedGenericThis.ts, 2, 24)) +>this : Symbol(this, Decl(instantiateContextuallyTypedGenericThis.ts, 2, 36)) +>T : Symbol(T, Decl(instantiateContextuallyTypedGenericThis.ts, 1, 9)) +>dit : Symbol(dit, Decl(instantiateContextuallyTypedGenericThis.ts, 2, 44)) +>T : Symbol(T, Decl(instantiateContextuallyTypedGenericThis.ts, 1, 9)) +>T : Symbol(T, Decl(instantiateContextuallyTypedGenericThis.ts, 1, 9)) + + ): T[]; +>T : Symbol(T, Decl(instantiateContextuallyTypedGenericThis.ts, 1, 9)) +} + +let $: JQuery; +>$ : Symbol($, Decl(instantiateContextuallyTypedGenericThis.ts, 6, 3)) +>JQuery : Symbol(JQuery, Decl(instantiateContextuallyTypedGenericThis.ts, 0, 0)) + +let lines: string[]; +>lines : Symbol(lines, Decl(instantiateContextuallyTypedGenericThis.ts, 7, 3)) + +$.each(lines, function(dit) { +>$.each : Symbol(JQuery.each, Decl(instantiateContextuallyTypedGenericThis.ts, 0, 18)) +>$ : Symbol($, Decl(instantiateContextuallyTypedGenericThis.ts, 6, 3)) +>each : Symbol(JQuery.each, Decl(instantiateContextuallyTypedGenericThis.ts, 0, 18)) +>lines : Symbol(lines, Decl(instantiateContextuallyTypedGenericThis.ts, 7, 3)) +>dit : Symbol(dit, Decl(instantiateContextuallyTypedGenericThis.ts, 8, 23)) + + return dit.charAt(0) + this.charAt(1); +>dit.charAt : Symbol(String.charAt, Decl(lib.d.ts, --, --)) +>dit : Symbol(dit, Decl(instantiateContextuallyTypedGenericThis.ts, 8, 23)) +>charAt : Symbol(String.charAt, Decl(lib.d.ts, --, --)) +>this.charAt : Symbol(String.charAt, Decl(lib.d.ts, --, --)) +>this : Symbol(this, Decl(instantiateContextuallyTypedGenericThis.ts, 2, 36)) +>charAt : Symbol(String.charAt, Decl(lib.d.ts, --, --)) + +}); + diff --git a/tests/baselines/reference/instantiateContextuallyTypedGenericThis.types b/tests/baselines/reference/instantiateContextuallyTypedGenericThis.types new file mode 100644 index 00000000000..5cdce6b99fe --- /dev/null +++ b/tests/baselines/reference/instantiateContextuallyTypedGenericThis.types @@ -0,0 +1,53 @@ +=== tests/cases/compiler/instantiateContextuallyTypedGenericThis.ts === +interface JQuery { +>JQuery : JQuery + + each( +>each : (collection: T[], callback: (this: T, dit: T) => T) => T[] +>T : T + + collection: T[], callback: (this: T, dit: T) => T +>collection : T[] +>T : T +>callback : (this: T, dit: T) => T +>this : T +>T : T +>dit : T +>T : T +>T : T + + ): T[]; +>T : T +} + +let $: JQuery; +>$ : JQuery +>JQuery : JQuery + +let lines: string[]; +>lines : string[] + +$.each(lines, function(dit) { +>$.each(lines, function(dit) { return dit.charAt(0) + this.charAt(1);}) : string[] +>$.each : (collection: T[], callback: (this: T, dit: T) => T) => T[] +>$ : JQuery +>each : (collection: T[], callback: (this: T, dit: T) => T) => T[] +>lines : string[] +>function(dit) { return dit.charAt(0) + this.charAt(1);} : (this: string, dit: string) => string +>dit : string + + return dit.charAt(0) + this.charAt(1); +>dit.charAt(0) + this.charAt(1) : string +>dit.charAt(0) : string +>dit.charAt : (pos: number) => string +>dit : string +>charAt : (pos: number) => string +>0 : number +>this.charAt(1) : string +>this.charAt : (pos: number) => string +>this : string +>charAt : (pos: number) => string +>1 : number + +}); + diff --git a/tests/baselines/reference/iterableArrayPattern29.errors.txt b/tests/baselines/reference/iterableArrayPattern29.errors.txt index b34d0317d57..29e5d0d2a3f 100644 --- a/tests/baselines/reference/iterableArrayPattern29.errors.txt +++ b/tests/baselines/reference/iterableArrayPattern29.errors.txt @@ -1,7 +1,6 @@ tests/cases/conformance/es6/destructuring/iterableArrayPattern29.ts(1,33): error TS2501: A rest element cannot contain a binding pattern. tests/cases/conformance/es6/destructuring/iterableArrayPattern29.ts(2,21): error TS2345: Argument of type '[string, boolean]' is not assignable to parameter of type '[string, number]'. - Types of property '1' are incompatible. - Type 'boolean' is not assignable to type 'number'. + Type 'boolean' is not assignable to type 'number'. ==== tests/cases/conformance/es6/destructuring/iterableArrayPattern29.ts (2 errors) ==== @@ -11,5 +10,4 @@ tests/cases/conformance/es6/destructuring/iterableArrayPattern29.ts(2,21): error takeFirstTwoEntries(...new Map([["", true], ["hello", true]])); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '[string, boolean]' is not assignable to parameter of type '[string, number]'. -!!! error TS2345: Types of property '1' are incompatible. -!!! error TS2345: Type 'boolean' is not assignable to type 'number'. \ No newline at end of file +!!! error TS2345: Type 'boolean' is not assignable to type 'number'. \ No newline at end of file diff --git a/tests/baselines/reference/jsdocNeverUndefinedNull.js b/tests/baselines/reference/jsdocNeverUndefinedNull.js new file mode 100644 index 00000000000..e57b7091a3b --- /dev/null +++ b/tests/baselines/reference/jsdocNeverUndefinedNull.js @@ -0,0 +1,20 @@ +//// [in.js] +/** + * @param {never} p1 + * @param {undefined} p2 + * @param {null} p3 + * @returns {void} nothing + */ +function f(p1, p2, p3) { +} + + +//// [out.js] +/** + * @param {never} p1 + * @param {undefined} p2 + * @param {null} p3 + * @returns {void} nothing + */ +function f(p1, p2, p3) { +} diff --git a/tests/baselines/reference/jsdocNeverUndefinedNull.symbols b/tests/baselines/reference/jsdocNeverUndefinedNull.symbols new file mode 100644 index 00000000000..a57636ed344 --- /dev/null +++ b/tests/baselines/reference/jsdocNeverUndefinedNull.symbols @@ -0,0 +1,14 @@ +=== tests/cases/conformance/jsdoc/in.js === +/** + * @param {never} p1 + * @param {undefined} p2 + * @param {null} p3 + * @returns {void} nothing + */ +function f(p1, p2, p3) { +>f : Symbol(f, Decl(in.js, 0, 0)) +>p1 : Symbol(p1, Decl(in.js, 6, 11)) +>p2 : Symbol(p2, Decl(in.js, 6, 14)) +>p3 : Symbol(p3, Decl(in.js, 6, 18)) +} + diff --git a/tests/baselines/reference/jsdocNeverUndefinedNull.types b/tests/baselines/reference/jsdocNeverUndefinedNull.types new file mode 100644 index 00000000000..fe57cc298e2 --- /dev/null +++ b/tests/baselines/reference/jsdocNeverUndefinedNull.types @@ -0,0 +1,14 @@ +=== tests/cases/conformance/jsdoc/in.js === +/** + * @param {never} p1 + * @param {undefined} p2 + * @param {null} p3 + * @returns {void} nothing + */ +function f(p1, p2, p3) { +>f : (p1: never, p2: undefined, p3: null) => void +>p1 : never +>p2 : undefined +>p3 : null +} + diff --git a/tests/baselines/reference/maxNodeModuleJsDepthDefaultsToZero.errors.txt b/tests/baselines/reference/maxNodeModuleJsDepthDefaultsToZero.errors.txt new file mode 100644 index 00000000000..2218e7910ae --- /dev/null +++ b/tests/baselines/reference/maxNodeModuleJsDepthDefaultsToZero.errors.txt @@ -0,0 +1,26 @@ +/index.ts(4,5): error TS2339: Property 'y' does not exist on type 'typeof "shortid"'. + + +==== /index.ts (1 errors) ==== + /// + import * as foo from "shortid"; + foo.x // found in index.d.ts + foo.y // ignored from shortid/index.js + ~ +!!! error TS2339: Property 'y' does not exist on type 'typeof "shortid"'. + + +==== /node_modules/shortid/node_modules/z/index.js (0 errors) ==== + // z will not be found because maxNodeModulesJsDepth: 0 + module.exports = { z: 'no' }; + +==== /node_modules/shortid/index.js (0 errors) ==== + var z = require('z'); + var y = { y: 'foo' }; + module.exports = y; + +==== /typings/index.d.ts (0 errors) ==== + declare module "shortid" { + export var x: number; + } + \ No newline at end of file diff --git a/tests/baselines/reference/maxNodeModuleJsDepthDefaultsToZero.trace.json b/tests/baselines/reference/maxNodeModuleJsDepthDefaultsToZero.trace.json new file mode 100644 index 00000000000..e53b2a0934f --- /dev/null +++ b/tests/baselines/reference/maxNodeModuleJsDepthDefaultsToZero.trace.json @@ -0,0 +1,28 @@ +[ + "======== Resolving module 'shortid' from '/index.ts'. ========", + "Explicitly specified module resolution kind: 'NodeJs'.", + "Loading module 'shortid' from 'node_modules' folder.", + "File '/node_modules/shortid.ts' does not exist.", + "File '/node_modules/shortid.tsx' does not exist.", + "File '/node_modules/shortid.d.ts' does not exist.", + "File '/node_modules/shortid.js' does not exist.", + "File '/node_modules/shortid.jsx' does not exist.", + "File '/node_modules/shortid/package.json' does not exist.", + "File '/node_modules/shortid/index.ts' does not exist.", + "File '/node_modules/shortid/index.tsx' does not exist.", + "File '/node_modules/shortid/index.d.ts' does not exist.", + "File '/node_modules/shortid/index.js' exist - use it as a name resolution result.", + "File '/node_modules/@types/shortid.ts' does not exist.", + "File '/node_modules/@types/shortid.tsx' does not exist.", + "File '/node_modules/@types/shortid.d.ts' does not exist.", + "File '/node_modules/@types/shortid.js' does not exist.", + "File '/node_modules/@types/shortid.jsx' does not exist.", + "File '/node_modules/@types/shortid/package.json' does not exist.", + "File '/node_modules/@types/shortid/index.ts' does not exist.", + "File '/node_modules/@types/shortid/index.tsx' does not exist.", + "File '/node_modules/@types/shortid/index.d.ts' does not exist.", + "File '/node_modules/@types/shortid/index.js' does not exist.", + "File '/node_modules/@types/shortid/index.jsx' does not exist.", + "Resolving real path for '/node_modules/shortid/index.js', result '/node_modules/shortid/index.js'", + "======== Module name 'shortid' was successfully resolved to '/node_modules/shortid/index.js'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/nativeToBoxedTypes.errors.txt b/tests/baselines/reference/nativeToBoxedTypes.errors.txt new file mode 100644 index 00000000000..03186a6d7e3 --- /dev/null +++ b/tests/baselines/reference/nativeToBoxedTypes.errors.txt @@ -0,0 +1,36 @@ +tests/cases/compiler/nativeToBoxedTypes.ts(3,1): error TS2322: Type 'Number' is not assignable to type 'number'. + 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible. +tests/cases/compiler/nativeToBoxedTypes.ts(7,1): error TS2322: Type 'String' is not assignable to type 'string'. + 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. +tests/cases/compiler/nativeToBoxedTypes.ts(11,1): error TS2322: Type 'Boolean' is not assignable to type 'boolean'. + 'boolean' is a primitive, but 'Boolean' is a wrapper object. Prefer using 'boolean' when possible. +tests/cases/compiler/nativeToBoxedTypes.ts(14,10): error TS2304: Cannot find name 'Symbol'. + + +==== tests/cases/compiler/nativeToBoxedTypes.ts (4 errors) ==== + var N = new Number(); + var n = 100; + n = N; + ~ +!!! error TS2322: Type 'Number' is not assignable to type 'number'. +!!! error TS2322: 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible. + + var S = new String(); + var s = "foge"; + s = S; + ~ +!!! error TS2322: Type 'String' is not assignable to type 'string'. +!!! error TS2322: 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. + + var B = new Boolean(); + var b = true; + b = B; + ~ +!!! error TS2322: Type 'Boolean' is not assignable to type 'boolean'. +!!! error TS2322: 'boolean' is a primitive, but 'Boolean' is a wrapper object. Prefer using 'boolean' when possible. + + var sym: symbol; + var Sym: Symbol; + ~~~~~~ +!!! error TS2304: Cannot find name 'Symbol'. + sym = Sym; \ No newline at end of file diff --git a/tests/baselines/reference/nativeToBoxedTypes.js b/tests/baselines/reference/nativeToBoxedTypes.js new file mode 100644 index 00000000000..db47c72fa10 --- /dev/null +++ b/tests/baselines/reference/nativeToBoxedTypes.js @@ -0,0 +1,30 @@ +//// [nativeToBoxedTypes.ts] +var N = new Number(); +var n = 100; +n = N; + +var S = new String(); +var s = "foge"; +s = S; + +var B = new Boolean(); +var b = true; +b = B; + +var sym: symbol; +var Sym: Symbol; +sym = Sym; + +//// [nativeToBoxedTypes.js] +var N = new Number(); +var n = 100; +n = N; +var S = new String(); +var s = "foge"; +s = S; +var B = new Boolean(); +var b = true; +b = B; +var sym; +var Sym; +sym = Sym; diff --git a/tests/baselines/reference/optionalBindingParameters1.errors.txt b/tests/baselines/reference/optionalBindingParameters1.errors.txt index 78fc1cbddf1..0780c626baf 100644 --- a/tests/baselines/reference/optionalBindingParameters1.errors.txt +++ b/tests/baselines/reference/optionalBindingParameters1.errors.txt @@ -1,7 +1,6 @@ tests/cases/conformance/es6/destructuring/optionalBindingParameters1.ts(2,14): error TS2463: A binding pattern parameter cannot be optional in an implementation signature. tests/cases/conformance/es6/destructuring/optionalBindingParameters1.ts(8,5): error TS2345: Argument of type '[boolean, number, string]' is not assignable to parameter of type '[string, number, boolean]'. - Types of property '0' are incompatible. - Type 'boolean' is not assignable to type 'string'. + Type 'boolean' is not assignable to type 'string'. ==== tests/cases/conformance/es6/destructuring/optionalBindingParameters1.ts (2 errors) ==== @@ -17,5 +16,4 @@ tests/cases/conformance/es6/destructuring/optionalBindingParameters1.ts(8,5): er foo([false, 0, ""]); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '[boolean, number, string]' is not assignable to parameter of type '[string, number, boolean]'. -!!! error TS2345: Types of property '0' are incompatible. -!!! error TS2345: Type 'boolean' is not assignable to type 'string'. \ No newline at end of file +!!! error TS2345: Type 'boolean' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/optionalBindingParametersInOverloads1.errors.txt b/tests/baselines/reference/optionalBindingParametersInOverloads1.errors.txt index 312603d2c2e..30ec4037c88 100644 --- a/tests/baselines/reference/optionalBindingParametersInOverloads1.errors.txt +++ b/tests/baselines/reference/optionalBindingParametersInOverloads1.errors.txt @@ -1,6 +1,5 @@ tests/cases/conformance/es6/destructuring/optionalBindingParametersInOverloads1.ts(9,5): error TS2345: Argument of type '[boolean, number, string]' is not assignable to parameter of type '[string, number, boolean]'. - Types of property '0' are incompatible. - Type 'boolean' is not assignable to type 'string'. + Type 'boolean' is not assignable to type 'string'. ==== tests/cases/conformance/es6/destructuring/optionalBindingParametersInOverloads1.ts (1 errors) ==== @@ -15,5 +14,4 @@ tests/cases/conformance/es6/destructuring/optionalBindingParametersInOverloads1. foo([false, 0, ""]); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '[boolean, number, string]' is not assignable to parameter of type '[string, number, boolean]'. -!!! error TS2345: Types of property '0' are incompatible. -!!! error TS2345: Type 'boolean' is not assignable to type 'string'. \ No newline at end of file +!!! error TS2345: Type 'boolean' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/optionalMethods.js b/tests/baselines/reference/optionalMethods.js index 42decf512e4..98629f5718b 100644 --- a/tests/baselines/reference/optionalMethods.js +++ b/tests/baselines/reference/optionalMethods.js @@ -126,7 +126,7 @@ interface Foo { } declare function test1(x: Foo): void; declare class Bar { - d?: number; + d: number; e: number; a: number; b?: number; diff --git a/tests/baselines/reference/primitiveMembers.errors.txt b/tests/baselines/reference/primitiveMembers.errors.txt index da8b75f9bc5..49ef8c4e3cf 100644 --- a/tests/baselines/reference/primitiveMembers.errors.txt +++ b/tests/baselines/reference/primitiveMembers.errors.txt @@ -1,5 +1,6 @@ tests/cases/compiler/primitiveMembers.ts(5,3): error TS2339: Property 'toBAZ' does not exist on type 'number'. tests/cases/compiler/primitiveMembers.ts(11,1): error TS2322: Type 'Number' is not assignable to type 'number'. + 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible. ==== tests/cases/compiler/primitiveMembers.ts (2 errors) ==== @@ -18,6 +19,7 @@ tests/cases/compiler/primitiveMembers.ts(11,1): error TS2322: Type 'Number' is n n = N; // should not work, as 'number' has a different brand ~ !!! error TS2322: Type 'Number' is not assignable to type 'number'. +!!! error TS2322: 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible. N = n; // should work var o: Object = {} diff --git a/tests/baselines/reference/symbolType15.errors.txt b/tests/baselines/reference/symbolType15.errors.txt index eb63e5798d5..205a2a999d0 100644 --- a/tests/baselines/reference/symbolType15.errors.txt +++ b/tests/baselines/reference/symbolType15.errors.txt @@ -1,4 +1,5 @@ tests/cases/conformance/es6/Symbols/symbolType15.ts(5,1): error TS2322: Type 'Symbol' is not assignable to type 'symbol'. + 'symbol' is a primitive, but 'Symbol' is a wrapper object. Prefer using 'symbol' when possible. ==== tests/cases/conformance/es6/Symbols/symbolType15.ts (1 errors) ==== @@ -8,4 +9,5 @@ tests/cases/conformance/es6/Symbols/symbolType15.ts(5,1): error TS2322: Type 'Sy symObj = sym; sym = symObj; ~~~ -!!! error TS2322: Type 'Symbol' is not assignable to type 'symbol'. \ No newline at end of file +!!! error TS2322: Type 'Symbol' is not assignable to type 'symbol'. +!!! error TS2322: 'symbol' is a primitive, but 'Symbol' is a wrapper object. Prefer using 'symbol' when possible. \ No newline at end of file diff --git a/tests/baselines/reference/thisTypeInFunctions.symbols b/tests/baselines/reference/thisTypeInFunctions.symbols index 8a0be7427ed..ad16785f288 100644 --- a/tests/baselines/reference/thisTypeInFunctions.symbols +++ b/tests/baselines/reference/thisTypeInFunctions.symbols @@ -135,7 +135,7 @@ let impl: I = { return this.a; >this.a : Symbol(a, Decl(thisTypeInFunctions.ts, 24, 30)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 24, 28)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 24, 23)) >a : Symbol(a, Decl(thisTypeInFunctions.ts, 24, 30)) }, @@ -144,7 +144,7 @@ let impl: I = { return this.a; >this.a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) ->this : Symbol(I, Decl(thisTypeInFunctions.ts, 19, 21)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 25, 22)) >a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) }, @@ -153,7 +153,7 @@ let impl: I = { return this.a; >this.a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) ->this : Symbol(I, Decl(thisTypeInFunctions.ts, 19, 21)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 26, 17)) >a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) }, @@ -173,7 +173,7 @@ impl.explicitStructural = function() { return this.a; }; >impl : Symbol(impl, Decl(thisTypeInFunctions.ts, 37, 3)) >explicitStructural : Symbol(I.explicitStructural, Decl(thisTypeInFunctions.ts, 23, 38)) >this.a : Symbol(a, Decl(thisTypeInFunctions.ts, 24, 30)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 24, 28)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 24, 23)) >a : Symbol(a, Decl(thisTypeInFunctions.ts, 24, 30)) impl.explicitInterface = function() { return this.a; }; @@ -181,7 +181,7 @@ impl.explicitInterface = function() { return this.a; }; >impl : Symbol(impl, Decl(thisTypeInFunctions.ts, 37, 3)) >explicitInterface : Symbol(I.explicitInterface, Decl(thisTypeInFunctions.ts, 24, 50)) >this.a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) ->this : Symbol(I, Decl(thisTypeInFunctions.ts, 19, 21)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 25, 22)) >a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) impl.explicitStructural = () => 12; @@ -199,7 +199,7 @@ impl.explicitThis = function () { return this.a; }; >impl : Symbol(impl, Decl(thisTypeInFunctions.ts, 37, 3)) >explicitThis : Symbol(I.explicitThis, Decl(thisTypeInFunctions.ts, 25, 39)) >this.a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) ->this : Symbol(I, Decl(thisTypeInFunctions.ts, 19, 21)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 26, 17)) >a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) // parameter checking @@ -536,7 +536,7 @@ c.explicitC = function(m) { return this.n + m }; >explicitC : Symbol(C.explicitC, Decl(thisTypeInFunctions.ts, 8, 5)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 126, 23)) >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 9, 14)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 126, 23)) @@ -546,7 +546,7 @@ c.explicitProperty = function(m) { return this.n + m }; >explicitProperty : Symbol(C.explicitProperty, Decl(thisTypeInFunctions.ts, 11, 5)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 127, 30)) >this.n : Symbol(n, Decl(thisTypeInFunctions.ts, 12, 28)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 12, 26)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 12, 21)) >n : Symbol(n, Decl(thisTypeInFunctions.ts, 12, 28)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 127, 30)) @@ -556,7 +556,7 @@ c.explicitThis = function(m) { return this.n + m }; >explicitThis : Symbol(C.explicitThis, Decl(thisTypeInFunctions.ts, 5, 14)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 128, 26)) >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 6, 17)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 128, 26)) diff --git a/tests/baselines/reference/thisTypeInFunctions.types b/tests/baselines/reference/thisTypeInFunctions.types index 24c4fb87baf..863ecbce628 100644 --- a/tests/baselines/reference/thisTypeInFunctions.types +++ b/tests/baselines/reference/thisTypeInFunctions.types @@ -132,7 +132,7 @@ function implicitThis(n: number): number { let impl: I = { >impl : I >I : I ->{ a: 12, explicitVoid2: () => this.a, // ok, this: any because it refers to some outer object (window?) explicitVoid1() { return 12; }, explicitStructural() { return this.a; }, explicitInterface() { return this.a; }, explicitThis() { return this.a; },} : { a: number; explicitVoid2: () => any; explicitVoid1(): number; explicitStructural(): number; explicitInterface(): number; explicitThis(): number; } +>{ a: 12, explicitVoid2: () => this.a, // ok, this: any because it refers to some outer object (window?) explicitVoid1() { return 12; }, explicitStructural() { return this.a; }, explicitInterface() { return this.a; }, explicitThis() { return this.a; },} : { a: number; explicitVoid2: () => any; explicitVoid1(this: void): number; explicitStructural(this: { a: number; }): number; explicitInterface(this: I): number; explicitThis(this: I): number; } a: 12, >a : number @@ -146,11 +146,11 @@ let impl: I = { >a : any explicitVoid1() { return 12; }, ->explicitVoid1 : () => number +>explicitVoid1 : (this: void) => number >12 : number explicitStructural() { ->explicitStructural : () => number +>explicitStructural : (this: { a: number; }) => number return this.a; >this.a : number @@ -159,7 +159,7 @@ let impl: I = { }, explicitInterface() { ->explicitInterface : () => number +>explicitInterface : (this: I) => number return this.a; >this.a : number @@ -168,7 +168,7 @@ let impl: I = { }, explicitThis() { ->explicitThis : () => number +>explicitThis : (this: I) => number return this.a; >this.a : number @@ -178,11 +178,11 @@ let impl: I = { }, } impl.explicitVoid1 = function () { return 12; }; ->impl.explicitVoid1 = function () { return 12; } : () => number +>impl.explicitVoid1 = function () { return 12; } : (this: void) => number >impl.explicitVoid1 : (this: void) => number >impl : I >explicitVoid1 : (this: void) => number ->function () { return 12; } : () => number +>function () { return 12; } : (this: void) => number >12 : number impl.explicitVoid2 = () => 12; @@ -194,21 +194,21 @@ impl.explicitVoid2 = () => 12; >12 : number impl.explicitStructural = function() { return this.a; }; ->impl.explicitStructural = function() { return this.a; } : () => number +>impl.explicitStructural = function() { return this.a; } : (this: { a: number; }) => number >impl.explicitStructural : (this: { a: number; }) => number >impl : I >explicitStructural : (this: { a: number; }) => number ->function() { return this.a; } : () => number +>function() { return this.a; } : (this: { a: number; }) => number >this.a : number >this : { a: number; } >a : number impl.explicitInterface = function() { return this.a; }; ->impl.explicitInterface = function() { return this.a; } : () => number +>impl.explicitInterface = function() { return this.a; } : (this: I) => number >impl.explicitInterface : (this: I) => number >impl : I >explicitInterface : (this: I) => number ->function() { return this.a; } : () => number +>function() { return this.a; } : (this: I) => number >this.a : number >this : I >a : number @@ -230,11 +230,11 @@ impl.explicitInterface = () => 12; >12 : number impl.explicitThis = function () { return this.a; }; ->impl.explicitThis = function () { return this.a; } : () => number +>impl.explicitThis = function () { return this.a; } : (this: I) => number >impl.explicitThis : (this: I) => number >impl : I >explicitThis : (this: I) => number ->function () { return this.a; } : () => number +>function () { return this.a; } : (this: I) => number >this.a : number >this : I >a : number @@ -433,7 +433,7 @@ let unboundToSpecified: (this: { y: number }, x: number) => number = x => x + th >this : { y: number; } >y : number >x : number ->x => x + this.y : (x: number) => any +>x => x + this.y : (this: { y: number; }, x: number) => any >x : number >x + this.y : any >x : number @@ -472,7 +472,7 @@ let specifiedLambda: (this: void, x: number) => number = x => x + 12; >specifiedLambda : (this: void, x: number) => number >this : void >x : number ->x => x + 12 : (x: number) => number +>x => x + 12 : (this: void, x: number) => number >x : number >x + 12 : number >x : number @@ -560,40 +560,40 @@ c.explicitProperty = reconstructed.explicitProperty; // lambdas are assignable to anything c.explicitC = m => m; ->c.explicitC = m => m : (m: number) => number +>c.explicitC = m => m : (this: C, m: number) => number >c.explicitC : (this: C, m: number) => number >c : C >explicitC : (this: C, m: number) => number ->m => m : (m: number) => number +>m => m : (this: C, m: number) => number >m : number >m : number c.explicitThis = m => m; ->c.explicitThis = m => m : (m: number) => number +>c.explicitThis = m => m : (this: C, m: number) => number >c.explicitThis : (this: C, m: number) => number >c : C >explicitThis : (this: C, m: number) => number ->m => m : (m: number) => number +>m => m : (this: C, m: number) => number >m : number >m : number c.explicitProperty = m => m; ->c.explicitProperty = m => m : (m: number) => number +>c.explicitProperty = m => m : (this: { n: number; }, m: number) => number >c.explicitProperty : (this: { n: number; }, m: number) => number >c : C >explicitProperty : (this: { n: number; }, m: number) => number ->m => m : (m: number) => number +>m => m : (this: { n: number; }, m: number) => number >m : number >m : number // this inside lambdas refer to outer scope // the outer-scoped lambda at top-level is still just `any` c.explicitC = m => m + this.n; ->c.explicitC = m => m + this.n : (m: number) => any +>c.explicitC = m => m + this.n : (this: C, m: number) => any >c.explicitC : (this: C, m: number) => number >c : C >explicitC : (this: C, m: number) => number ->m => m + this.n : (m: number) => any +>m => m + this.n : (this: C, m: number) => any >m : number >m + this.n : any >m : number @@ -602,11 +602,11 @@ c.explicitC = m => m + this.n; >n : any c.explicitThis = m => m + this.n; ->c.explicitThis = m => m + this.n : (m: number) => any +>c.explicitThis = m => m + this.n : (this: C, m: number) => any >c.explicitThis : (this: C, m: number) => number >c : C >explicitThis : (this: C, m: number) => number ->m => m + this.n : (m: number) => any +>m => m + this.n : (this: C, m: number) => any >m : number >m + this.n : any >m : number @@ -615,11 +615,11 @@ c.explicitThis = m => m + this.n; >n : any c.explicitProperty = m => m + this.n; ->c.explicitProperty = m => m + this.n : (m: number) => any +>c.explicitProperty = m => m + this.n : (this: { n: number; }, m: number) => any >c.explicitProperty : (this: { n: number; }, m: number) => number >c : C >explicitProperty : (this: { n: number; }, m: number) => number ->m => m + this.n : (m: number) => any +>m => m + this.n : (this: { n: number; }, m: number) => any >m : number >m + this.n : any >m : number @@ -652,11 +652,11 @@ c.explicitThis = function(this: C, m: number) { return this.n + m }; // this:any compatibility c.explicitC = function(m) { return this.n + m }; ->c.explicitC = function(m) { return this.n + m } : (m: number) => number +>c.explicitC = function(m) { return this.n + m } : (this: C, m: number) => number >c.explicitC : (this: C, m: number) => number >c : C >explicitC : (this: C, m: number) => number ->function(m) { return this.n + m } : (m: number) => number +>function(m) { return this.n + m } : (this: C, m: number) => number >m : number >this.n + m : number >this.n : number @@ -665,11 +665,11 @@ c.explicitC = function(m) { return this.n + m }; >m : number c.explicitProperty = function(m) { return this.n + m }; ->c.explicitProperty = function(m) { return this.n + m } : (m: number) => number +>c.explicitProperty = function(m) { return this.n + m } : (this: { n: number; }, m: number) => number >c.explicitProperty : (this: { n: number; }, m: number) => number >c : C >explicitProperty : (this: { n: number; }, m: number) => number ->function(m) { return this.n + m } : (m: number) => number +>function(m) { return this.n + m } : (this: { n: number; }, m: number) => number >m : number >this.n + m : number >this.n : number @@ -678,11 +678,11 @@ c.explicitProperty = function(m) { return this.n + m }; >m : number c.explicitThis = function(m) { return this.n + m }; ->c.explicitThis = function(m) { return this.n + m } : (m: number) => number +>c.explicitThis = function(m) { return this.n + m } : (this: C, m: number) => number >c.explicitThis : (this: C, m: number) => number >c : C >explicitThis : (this: C, m: number) => number ->function(m) { return this.n + m } : (m: number) => number +>function(m) { return this.n + m } : (this: C, m: number) => number >m : number >this.n + m : number >this.n : number @@ -723,11 +723,11 @@ c.explicitC = function(this: B, m: number) { return this.n + m }; // this:void compatibility c.explicitVoid = n => n; ->c.explicitVoid = n => n : (n: number) => number +>c.explicitVoid = n => n : (this: void, n: number) => number >c.explicitVoid : (this: void, m: number) => number >c : C >explicitVoid : (this: void, m: number) => number ->n => n : (n: number) => number +>n => n : (this: void, n: number) => number >n : number >n : number diff --git a/tests/baselines/reference/thisTypeInFunctions2.symbols b/tests/baselines/reference/thisTypeInFunctions2.symbols index cdc7fb321d4..5cc26e3ad43 100644 --- a/tests/baselines/reference/thisTypeInFunctions2.symbols +++ b/tests/baselines/reference/thisTypeInFunctions2.symbols @@ -61,12 +61,12 @@ extend1({ >init : Symbol(init, Decl(thisTypeInFunctions2.ts, 20, 9)) this // this: IndexedWithThis because of contextual typing. ->this : Symbol(IndexedWithThis, Decl(thisTypeInFunctions2.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInFunctions2.ts, 2, 12)) // this.mine this.willDestroy >this.willDestroy : Symbol(IndexedWithThis.willDestroy, Decl(thisTypeInFunctions2.ts, 2, 32)) ->this : Symbol(IndexedWithThis, Decl(thisTypeInFunctions2.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInFunctions2.ts, 2, 12)) >willDestroy : Symbol(IndexedWithThis.willDestroy, Decl(thisTypeInFunctions2.ts, 2, 32)) }, @@ -77,7 +77,10 @@ extend1({ >foo : Symbol(foo, Decl(thisTypeInFunctions2.ts, 26, 13)) this.url; // this: any because 'foo' matches the string indexer +>this : Symbol(this, Decl(thisTypeInFunctions2.ts, 4, 87)) + this.willDestroy; +>this : Symbol(this, Decl(thisTypeInFunctions2.ts, 4, 87)) } }); extend2({ diff --git a/tests/baselines/reference/thisTypeInFunctions2.types b/tests/baselines/reference/thisTypeInFunctions2.types index 371b5f5cafc..25fb2f28a60 100644 --- a/tests/baselines/reference/thisTypeInFunctions2.types +++ b/tests/baselines/reference/thisTypeInFunctions2.types @@ -58,10 +58,10 @@ declare function simple(arg: SimpleInterface): void; extend1({ >extend1({ init() { this // this: IndexedWithThis because of contextual typing. // this.mine this.willDestroy }, mine: 12, foo() { this.url; // this: any because 'foo' matches the string indexer this.willDestroy; }}) : void >extend1 : (args: IndexedWithThis) => void ->{ init() { this // this: IndexedWithThis because of contextual typing. // this.mine this.willDestroy }, mine: 12, foo() { this.url; // this: any because 'foo' matches the string indexer this.willDestroy; }} : { init(): void; mine: number; foo(): void; } +>{ init() { this // this: IndexedWithThis because of contextual typing. // this.mine this.willDestroy }, mine: 12, foo() { this.url; // this: any because 'foo' matches the string indexer this.willDestroy; }} : { init(this: IndexedWithThis): void; mine: number; foo(this: any): void; } init() { ->init : () => void +>init : (this: IndexedWithThis) => void this // this: IndexedWithThis because of contextual typing. >this : IndexedWithThis @@ -78,7 +78,7 @@ extend1({ >12 : number foo() { ->foo : () => void +>foo : (this: any) => void this.url; // this: any because 'foo' matches the string indexer >this.url : any diff --git a/tests/baselines/reference/tsxDefaultImports.js b/tests/baselines/reference/tsxDefaultImports.js new file mode 100644 index 00000000000..79f5d2b8fa1 --- /dev/null +++ b/tests/baselines/reference/tsxDefaultImports.js @@ -0,0 +1,34 @@ +//// [tests/cases/compiler/tsxDefaultImports.ts] //// + +//// [a.ts] + +enum SomeEnum { + one, +} +export default class SomeClass { + public static E = SomeEnum; +} + +//// [b.ts] +import {default as Def} from "./a" +let a = Def.E.one; + + +//// [a.js] +"use strict"; +var SomeEnum; +(function (SomeEnum) { + SomeEnum[SomeEnum["one"] = 0] = "one"; +})(SomeEnum || (SomeEnum = {})); +var SomeClass = (function () { + function SomeClass() { + } + SomeClass.E = SomeEnum; + return SomeClass; +}()); +exports.__esModule = true; +exports["default"] = SomeClass; +//// [b.js] +"use strict"; +var a_1 = require("./a"); +var a = a_1["default"].E.one; diff --git a/tests/baselines/reference/tsxDefaultImports.symbols b/tests/baselines/reference/tsxDefaultImports.symbols new file mode 100644 index 00000000000..e42392e24aa --- /dev/null +++ b/tests/baselines/reference/tsxDefaultImports.symbols @@ -0,0 +1,29 @@ +=== tests/cases/compiler/a.ts === + +enum SomeEnum { +>SomeEnum : Symbol(SomeEnum, Decl(a.ts, 0, 0)) + + one, +>one : Symbol(SomeEnum.one, Decl(a.ts, 1, 15)) +} +export default class SomeClass { +>SomeClass : Symbol(SomeClass, Decl(a.ts, 3, 1)) + + public static E = SomeEnum; +>E : Symbol(SomeClass.E, Decl(a.ts, 4, 32)) +>SomeEnum : Symbol(SomeEnum, Decl(a.ts, 0, 0)) +} + +=== tests/cases/compiler/b.ts === +import {default as Def} from "./a" +>default : Symbol(Def, Decl(b.ts, 0, 8)) +>Def : Symbol(Def, Decl(b.ts, 0, 8)) + +let a = Def.E.one; +>a : Symbol(a, Decl(b.ts, 1, 3)) +>Def.E.one : Symbol(SomeEnum.one, Decl(a.ts, 1, 15)) +>Def.E : Symbol(Def.E, Decl(a.ts, 4, 32)) +>Def : Symbol(Def, Decl(b.ts, 0, 8)) +>E : Symbol(Def.E, Decl(a.ts, 4, 32)) +>one : Symbol(SomeEnum.one, Decl(a.ts, 1, 15)) + diff --git a/tests/baselines/reference/tsxDefaultImports.types b/tests/baselines/reference/tsxDefaultImports.types new file mode 100644 index 00000000000..a9bdedf3efd --- /dev/null +++ b/tests/baselines/reference/tsxDefaultImports.types @@ -0,0 +1,29 @@ +=== tests/cases/compiler/a.ts === + +enum SomeEnum { +>SomeEnum : SomeEnum + + one, +>one : SomeEnum +} +export default class SomeClass { +>SomeClass : SomeClass + + public static E = SomeEnum; +>E : typeof SomeEnum +>SomeEnum : typeof SomeEnum +} + +=== tests/cases/compiler/b.ts === +import {default as Def} from "./a" +>default : typeof Def +>Def : typeof Def + +let a = Def.E.one; +>a : SomeEnum +>Def.E.one : SomeEnum +>Def.E : typeof SomeEnum +>Def : typeof Def +>E : typeof SomeEnum +>one : SomeEnum + diff --git a/tests/baselines/reference/tupleTypes.errors.txt b/tests/baselines/reference/tupleTypes.errors.txt index 75f413eb170..3b55476e4b1 100644 --- a/tests/baselines/reference/tupleTypes.errors.txt +++ b/tests/baselines/reference/tupleTypes.errors.txt @@ -4,8 +4,7 @@ tests/cases/compiler/tupleTypes.ts(14,1): error TS2322: Type 'undefined[]' is no tests/cases/compiler/tupleTypes.ts(15,1): error TS2322: Type '[number]' is not assignable to type '[number, string]'. Property '1' is missing in type '[number]'. tests/cases/compiler/tupleTypes.ts(17,1): error TS2322: Type '[string, number]' is not assignable to type '[number, string]'. - Types of property '0' are incompatible. - Type 'string' is not assignable to type 'number'. + Type 'string' is not assignable to type 'number'. tests/cases/compiler/tupleTypes.ts(41,1): error TS2322: Type 'undefined[]' is not assignable to type '[number, string]'. tests/cases/compiler/tupleTypes.ts(47,1): error TS2322: Type '[number, string]' is not assignable to type 'number[]'. Types of property 'pop' are incompatible. @@ -18,11 +17,9 @@ tests/cases/compiler/tupleTypes.ts(49,1): error TS2322: Type '[number, {}]' is n Type 'number | {}' is not assignable to type 'number'. Type '{}' is not assignable to type 'number'. tests/cases/compiler/tupleTypes.ts(50,1): error TS2322: Type '[number, number]' is not assignable to type '[number, string]'. - Types of property '1' are incompatible. - Type 'number' is not assignable to type 'string'. + Type 'number' is not assignable to type 'string'. tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is not assignable to type '[number, string]'. - Types of property '1' are incompatible. - Type '{}' is not assignable to type 'string'. + Type '{}' is not assignable to type 'string'. ==== tests/cases/compiler/tupleTypes.ts (9 errors) ==== @@ -53,8 +50,7 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n t = ["hello", 1]; // Error ~ !!! error TS2322: Type '[string, number]' is not assignable to type '[number, string]'. -!!! error TS2322: Types of property '0' are incompatible. -!!! error TS2322: Type 'string' is not assignable to type 'number'. +!!! error TS2322: Type 'string' is not assignable to type 'number'. t = [1, "hello", 2]; // Ok var tf: [string, (x: string) => number] = ["hello", x => x.length]; @@ -104,13 +100,11 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n a1 = a2; // Error ~~ !!! error TS2322: Type '[number, number]' is not assignable to type '[number, string]'. -!!! error TS2322: Types of property '1' are incompatible. -!!! error TS2322: Type 'number' is not assignable to type 'string'. +!!! error TS2322: Type 'number' is not assignable to type 'string'. a1 = a3; // Error ~~ !!! error TS2322: Type '[number, {}]' is not assignable to type '[number, string]'. -!!! error TS2322: Types of property '1' are incompatible. -!!! error TS2322: Type '{}' is not assignable to type 'string'. +!!! error TS2322: Type '{}' is not assignable to type 'string'. a3 = a1; a3 = a2; \ No newline at end of file diff --git a/tests/baselines/reference/typingsLookup4.js b/tests/baselines/reference/typingsLookup4.js new file mode 100644 index 00000000000..c11bc13c613 --- /dev/null +++ b/tests/baselines/reference/typingsLookup4.js @@ -0,0 +1,36 @@ +//// [tests/cases/conformance/typings/typingsLookup4.ts] //// + +//// [package.json] +{ "typings": "jquery.d.ts" } + +//// [jquery.d.ts] +export const j: number; + +//// [package.json] +{ "typings": "kquery" } + +//// [kquery.d.ts] +export const k: number; + +//// [package.json] +{ "typings": "lquery" } + +//// [lquery.ts] +export const l = 2; + +//// [a.ts] +import { j } from "jquery"; +import { k } from "kquery"; +import { l } from "lquery"; +j + k + l; + + +//// [lquery.js] +"use strict"; +exports.l = 2; +//// [a.js] +"use strict"; +var jquery_1 = require("jquery"); +var kquery_1 = require("kquery"); +var lquery_1 = require("lquery"); +jquery_1.j + kquery_1.k + lquery_1.l; diff --git a/tests/baselines/reference/typingsLookup4.symbols b/tests/baselines/reference/typingsLookup4.symbols new file mode 100644 index 00000000000..144548c6452 --- /dev/null +++ b/tests/baselines/reference/typingsLookup4.symbols @@ -0,0 +1,27 @@ +=== /a.ts === +import { j } from "jquery"; +>j : Symbol(j, Decl(a.ts, 0, 8)) + +import { k } from "kquery"; +>k : Symbol(k, Decl(a.ts, 1, 8)) + +import { l } from "lquery"; +>l : Symbol(l, Decl(a.ts, 2, 8)) + +j + k + l; +>j : Symbol(j, Decl(a.ts, 0, 8)) +>k : Symbol(k, Decl(a.ts, 1, 8)) +>l : Symbol(l, Decl(a.ts, 2, 8)) + +=== /node_modules/@types/jquery/jquery.d.ts === +export const j: number; +>j : Symbol(j, Decl(jquery.d.ts, 0, 12)) + +=== /node_modules/@types/kquery/kquery.d.ts === +export const k: number; +>k : Symbol(k, Decl(kquery.d.ts, 0, 12)) + +=== /node_modules/@types/lquery/lquery.ts === +export const l = 2; +>l : Symbol(l, Decl(lquery.ts, 0, 12)) + diff --git a/tests/baselines/reference/typingsLookup4.trace.json b/tests/baselines/reference/typingsLookup4.trace.json new file mode 100644 index 00000000000..4bca8456f58 --- /dev/null +++ b/tests/baselines/reference/typingsLookup4.trace.json @@ -0,0 +1,93 @@ +[ + "======== Resolving module 'jquery' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'jquery' from 'node_modules' folder.", + "File '/node_modules/jquery.ts' does not exist.", + "File '/node_modules/jquery.tsx' does not exist.", + "File '/node_modules/jquery.d.ts' does not exist.", + "File '/node_modules/jquery/package.json' does not exist.", + "File '/node_modules/jquery/index.ts' does not exist.", + "File '/node_modules/jquery/index.tsx' does not exist.", + "File '/node_modules/jquery/index.d.ts' does not exist.", + "File '/node_modules/@types/jquery.ts' does not exist.", + "File '/node_modules/@types/jquery.tsx' does not exist.", + "File '/node_modules/@types/jquery.d.ts' does not exist.", + "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", + "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", + "File '/node_modules/@types/jquery/jquery.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/jquery/jquery.d.ts', result '/node_modules/@types/jquery/jquery.d.ts'", + "======== Module name 'jquery' was successfully resolved to '/node_modules/@types/jquery/jquery.d.ts'. ========", + "======== Resolving module 'kquery' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'kquery' from 'node_modules' folder.", + "File '/node_modules/kquery.ts' does not exist.", + "File '/node_modules/kquery.tsx' does not exist.", + "File '/node_modules/kquery.d.ts' does not exist.", + "File '/node_modules/kquery/package.json' does not exist.", + "File '/node_modules/kquery/index.ts' does not exist.", + "File '/node_modules/kquery/index.tsx' does not exist.", + "File '/node_modules/kquery/index.d.ts' does not exist.", + "File '/node_modules/@types/kquery.ts' does not exist.", + "File '/node_modules/@types/kquery.tsx' does not exist.", + "File '/node_modules/@types/kquery.d.ts' does not exist.", + "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", + "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", + "File '/node_modules/@types/kquery/kquery' does not exist.", + "File '/node_modules/@types/kquery/kquery.ts' does not exist.", + "File '/node_modules/@types/kquery/kquery.tsx' does not exist.", + "File '/node_modules/@types/kquery/kquery.d.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/kquery/kquery.d.ts', result '/node_modules/@types/kquery/kquery.d.ts'", + "======== Module name 'kquery' was successfully resolved to '/node_modules/@types/kquery/kquery.d.ts'. ========", + "======== Resolving module 'lquery' from '/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'lquery' from 'node_modules' folder.", + "File '/node_modules/lquery.ts' does not exist.", + "File '/node_modules/lquery.tsx' does not exist.", + "File '/node_modules/lquery.d.ts' does not exist.", + "File '/node_modules/lquery/package.json' does not exist.", + "File '/node_modules/lquery/index.ts' does not exist.", + "File '/node_modules/lquery/index.tsx' does not exist.", + "File '/node_modules/lquery/index.d.ts' does not exist.", + "File '/node_modules/@types/lquery.ts' does not exist.", + "File '/node_modules/@types/lquery.tsx' does not exist.", + "File '/node_modules/@types/lquery.d.ts' does not exist.", + "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", + "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", + "File '/node_modules/@types/lquery/lquery' does not exist.", + "File '/node_modules/@types/lquery/lquery.ts' exist - use it as a name resolution result.", + "Resolving real path for '/node_modules/@types/lquery/lquery.ts', result '/node_modules/@types/lquery/lquery.ts'", + "======== Module name 'lquery' was successfully resolved to '/node_modules/@types/lquery/lquery.ts'. ========", + "======== Resolving type reference directive 'jquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", + "Resolving with primary search path '/node_modules/@types'", + "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", + "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", + "File '/node_modules/@types/jquery/jquery.d.ts' exist - use it as a name resolution result.", + "======== Type reference directive 'jquery' was successfully resolved to '/node_modules/@types/jquery/jquery.d.ts', primary: true. ========", + "======== Resolving type reference directive 'kquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", + "Resolving with primary search path '/node_modules/@types'", + "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", + "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", + "File '/node_modules/@types/kquery/kquery' does not exist.", + "File '/node_modules/@types/kquery/kquery.d.ts' exist - use it as a name resolution result.", + "======== Type reference directive 'kquery' was successfully resolved to '/node_modules/@types/kquery/kquery.d.ts', primary: true. ========", + "======== Resolving type reference directive 'lquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", + "Resolving with primary search path '/node_modules/@types'", + "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", + "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", + "File '/node_modules/@types/lquery/lquery' does not exist.", + "File '/node_modules/@types/lquery/lquery.d.ts' does not exist.", + "File '/node_modules/@types/lquery/index.d.ts' does not exist.", + "Looking up in 'node_modules' folder, initial location '/'", + "File '/node_modules/lquery.ts' does not exist.", + "File '/node_modules/lquery.d.ts' does not exist.", + "File '/node_modules/lquery/package.json' does not exist.", + "File '/node_modules/lquery/index.ts' does not exist.", + "File '/node_modules/lquery/index.d.ts' does not exist.", + "File '/node_modules/@types/lquery.ts' does not exist.", + "File '/node_modules/@types/lquery.d.ts' does not exist.", + "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", + "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", + "File '/node_modules/@types/lquery/lquery' does not exist.", + "File '/node_modules/@types/lquery/lquery.ts' exist - use it as a name resolution result.", + "======== Type reference directive 'lquery' was successfully resolved to '/node_modules/@types/lquery/lquery.ts', primary: false. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typingsLookup4.types b/tests/baselines/reference/typingsLookup4.types new file mode 100644 index 00000000000..d922c7b1dfa --- /dev/null +++ b/tests/baselines/reference/typingsLookup4.types @@ -0,0 +1,30 @@ +=== /a.ts === +import { j } from "jquery"; +>j : number + +import { k } from "kquery"; +>k : number + +import { l } from "lquery"; +>l : number + +j + k + l; +>j + k + l : number +>j + k : number +>j : number +>k : number +>l : number + +=== /node_modules/@types/jquery/jquery.d.ts === +export const j: number; +>j : number + +=== /node_modules/@types/kquery/kquery.d.ts === +export const k: number; +>k : number + +=== /node_modules/@types/lquery/lquery.ts === +export const l = 2; +>l : number +>2 : number + diff --git a/tests/cases/compiler/errorForConflictingExportEqualsValue.ts b/tests/cases/compiler/errorForConflictingExportEqualsValue.ts new file mode 100644 index 00000000000..59af1f46690 --- /dev/null +++ b/tests/cases/compiler/errorForConflictingExportEqualsValue.ts @@ -0,0 +1,2 @@ +export var x; +export = {}; diff --git a/tests/cases/compiler/instantiateContextuallyTypedGenericThis.ts b/tests/cases/compiler/instantiateContextuallyTypedGenericThis.ts new file mode 100644 index 00000000000..f06f06ee7a1 --- /dev/null +++ b/tests/cases/compiler/instantiateContextuallyTypedGenericThis.ts @@ -0,0 +1,11 @@ +interface JQuery { + each( + collection: T[], callback: (this: T, dit: T) => T + ): T[]; +} + +let $: JQuery; +let lines: string[]; +$.each(lines, function(dit) { + return dit.charAt(0) + this.charAt(1); +}); diff --git a/tests/cases/compiler/maxNodeModuleJsDepthDefaultsToZero.ts b/tests/cases/compiler/maxNodeModuleJsDepthDefaultsToZero.ts new file mode 100644 index 00000000000..9d154ec1e59 --- /dev/null +++ b/tests/cases/compiler/maxNodeModuleJsDepthDefaultsToZero.ts @@ -0,0 +1,36 @@ +// @module: commonjs +// @moduleResolution: node +// @allowJs: true +// @traceResolution: true +// @noEmit: true + +// @filename: /tsconfig.json +{ + "compileOnSave": true, + "compilerOptions": { + "module": "commonjs", + "moduleResolution": "node", + "outDir": "bin" + }, + "exclude": [ "node_modules" ] +} +// @filename: /node_modules/shortid/node_modules/z/index.js +// z will not be found because maxNodeModulesJsDepth: 0 +module.exports = { z: 'no' }; + +// @filename: /node_modules/shortid/index.js +var z = require('z'); +var y = { y: 'foo' }; +module.exports = y; + +// @filename: /typings/index.d.ts +declare module "shortid" { + export var x: number; +} + +// @filename: /index.ts +/// +import * as foo from "shortid"; +foo.x // found in index.d.ts +foo.y // ignored from shortid/index.js + diff --git a/tests/cases/compiler/nativeToBoxedTypes.ts b/tests/cases/compiler/nativeToBoxedTypes.ts new file mode 100644 index 00000000000..a34dd5cdd3b --- /dev/null +++ b/tests/cases/compiler/nativeToBoxedTypes.ts @@ -0,0 +1,15 @@ +var N = new Number(); +var n = 100; +n = N; + +var S = new String(); +var s = "foge"; +s = S; + +var B = new Boolean(); +var b = true; +b = B; + +var sym: symbol; +var Sym: Symbol; +sym = Sym; \ No newline at end of file diff --git a/tests/cases/compiler/tsxDefaultImports.ts b/tests/cases/compiler/tsxDefaultImports.ts new file mode 100644 index 00000000000..4e313b33eac --- /dev/null +++ b/tests/cases/compiler/tsxDefaultImports.ts @@ -0,0 +1,12 @@ +// @Filename: a.ts + +enum SomeEnum { + one, +} +export default class SomeClass { + public static E = SomeEnum; +} + +// @Filename: b.ts +import {default as Def} from "./a" +let a = Def.E.one; diff --git a/tests/cases/conformance/async/es6/await_unaryExpression_es6.ts b/tests/cases/conformance/async/es6/await_unaryExpression_es6.ts new file mode 100644 index 00000000000..09cf0a87a5a --- /dev/null +++ b/tests/cases/conformance/async/es6/await_unaryExpression_es6.ts @@ -0,0 +1,17 @@ +// @target: es6 + +async function bar() { + !await 42; // OK +} + +async function bar1() { + +await 42; // OK +} + +async function bar3() { + -await 42; // OK +} + +async function bar4() { + ~await 42; // OK +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es6/await_unaryExpression_es6_1.ts b/tests/cases/conformance/async/es6/await_unaryExpression_es6_1.ts new file mode 100644 index 00000000000..5ccf1a1c35a --- /dev/null +++ b/tests/cases/conformance/async/es6/await_unaryExpression_es6_1.ts @@ -0,0 +1,21 @@ +// @target: es6 + +async function bar() { + !await 42; // OK +} + +async function bar1() { + delete await 42; // OK +} + +async function bar2() { + delete await 42; // OK +} + +async function bar3() { + void await 42; +} + +async function bar4() { + +await 42; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es6/await_unaryExpression_es6_2.ts b/tests/cases/conformance/async/es6/await_unaryExpression_es6_2.ts new file mode 100644 index 00000000000..24683765d19 --- /dev/null +++ b/tests/cases/conformance/async/es6/await_unaryExpression_es6_2.ts @@ -0,0 +1,13 @@ +// @target: es6 + +async function bar1() { + delete await 42; +} + +async function bar2() { + delete await 42; +} + +async function bar3() { + void await 42; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es6/await_unaryExpression_es6_3.ts b/tests/cases/conformance/async/es6/await_unaryExpression_es6_3.ts new file mode 100644 index 00000000000..b595ab5e748 --- /dev/null +++ b/tests/cases/conformance/async/es6/await_unaryExpression_es6_3.ts @@ -0,0 +1,19 @@ +// @target: es6 + +async function bar1() { + ++await 42; // Error +} + +async function bar2() { + --await 42; // Error +} + +async function bar3() { + var x = 42; + await x++; // OK but shouldn't need parenthesis +} + +async function bar4() { + var x = 42; + await x--; // OK but shouldn't need parenthesis +} \ No newline at end of file diff --git a/tests/cases/conformance/jsdoc/jsdocNeverUndefinedNull.ts b/tests/cases/conformance/jsdoc/jsdocNeverUndefinedNull.ts new file mode 100644 index 00000000000..c095bc1c920 --- /dev/null +++ b/tests/cases/conformance/jsdoc/jsdocNeverUndefinedNull.ts @@ -0,0 +1,11 @@ +// @allowJs: true +// @filename: in.js +// @out: out.js +/** + * @param {never} p1 + * @param {undefined} p2 + * @param {null} p3 + * @returns {void} nothing + */ +function f(p1, p2, p3) { +} diff --git a/tests/cases/conformance/typings/typingsLookup4.ts b/tests/cases/conformance/typings/typingsLookup4.ts new file mode 100644 index 00000000000..234090aebad --- /dev/null +++ b/tests/cases/conformance/typings/typingsLookup4.ts @@ -0,0 +1,31 @@ +// @traceResolution: true +// @noImplicitReferences: true +// @currentDirectory: / +// A file extension is optional in typings entries. + +// @filename: /tsconfig.json +{} + +// @filename: /node_modules/@types/jquery/package.json +{ "typings": "jquery.d.ts" } + +// @filename: /node_modules/@types/jquery/jquery.d.ts +export const j: number; + +// @filename: /node_modules/@types/kquery/package.json +{ "typings": "kquery" } + +// @filename: /node_modules/@types/kquery/kquery.d.ts +export const k: number; + +// @filename: /node_modules/@types/lquery/package.json +{ "typings": "lquery" } + +// @filename: /node_modules/@types/lquery/lquery.ts +export const l = 2; + +// @filename: /a.ts +import { j } from "jquery"; +import { k } from "kquery"; +import { l } from "lquery"; +j + k + l; diff --git a/tests/cases/fourslash/jsdocNullableUnion.ts b/tests/cases/fourslash/jsdocNullableUnion.ts new file mode 100644 index 00000000000..19dc9818d69 --- /dev/null +++ b/tests/cases/fourslash/jsdocNullableUnion.ts @@ -0,0 +1,23 @@ +/// +// @allowNonTsExtensions: true +// @Filename: Foo.js +//// +//// * @param {never | {x: string}} p1 +//// * @param {undefined | {y: number}} p2 +//// * @param {null | {z: boolean}} p3 +//// * @returns {void} nothing +//// */ +////function f(p1, p2, p3) { +//// p1./*1*/ +//// p2./*2*/ +//// p3./*3*/ +////} + +goTo.marker('1'); +verify.memberListContains("x"); + +goTo.marker('2'); +verify.memberListContains("y"); + +goTo.marker('3'); +verify.memberListContains("z"); diff --git a/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts b/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts new file mode 100644 index 00000000000..2c5e53ea224 --- /dev/null +++ b/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts @@ -0,0 +1,20 @@ +/// + +// @allowNonTsExtensions: true +// @Filename: a.js +//// /** +//// * Modify the parameter +//// * @param {string} p1 +//// */ +//// var foo = function (p1) { } +//// module.exports.foo = foo; +//// fo/*1*/ + +// @Filename: b.ts +//// import a = require("./a"); +//// a.fo/*2*/ + +goTo.marker('1'); +verify.completionEntryDetailIs("foo", "var foo: (p1: string) => void", "Modify the parameter"); +goTo.marker('2'); +verify.completionEntryDetailIs("foo", "(property) a.foo: (p1: string) => void", "Modify the parameter"); diff --git a/tests/cases/fourslash/syntacticClassificationsDocComment4.ts b/tests/cases/fourslash/syntacticClassificationsDocComment4.ts new file mode 100644 index 00000000000..d8ac2f12d8b --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsDocComment4.ts @@ -0,0 +1,24 @@ +/// + +//// /** @param {number} p1 */ +//// function foo(p1) {} + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("/** "), + c.punctuation("@"), + c.docCommentTagName("param"), + c.comment(" "), + c.punctuation("{"), + c.keyword("number"), + c.punctuation("}"), + c.comment(" "), + c.parameterName("p1"), + c.comment(" */"), + c.keyword("function"), + c.identifier("foo"), + c.punctuation("("), + c.parameterName("p1"), + c.punctuation(")"), + c.punctuation("{"), + c.punctuation("}")); diff --git a/tests/cases/projects/NodeModulesSearch/importHigher/tsconfig.json b/tests/cases/projects/NodeModulesSearch/importHigher/tsconfig.json index c7b95984b42..301db9c870a 100644 --- a/tests/cases/projects/NodeModulesSearch/importHigher/tsconfig.json +++ b/tests/cases/projects/NodeModulesSearch/importHigher/tsconfig.json @@ -2,6 +2,7 @@ "compilerOptions": { "allowJs": true, "declaration": false, - "moduleResolution": "node" + "moduleResolution": "node", + "maxNodeModuleJsDepth": 2 } }