diff --git a/lib/lib.core.es6.d.ts b/lib/lib.core.es6.d.ts index 857f5957a45..0470c4827cd 100644 --- a/lib/lib.core.es6.d.ts +++ b/lib/lib.core.es6.d.ts @@ -3847,7 +3847,7 @@ interface Symbol { /** Returns the primitive value of the specified object. */ valueOf(): Object; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "Symbol"; } interface SymbolConstructor { @@ -4405,7 +4405,7 @@ interface IterableIterator extends Iterator { } interface GeneratorFunction extends Function { - + [Symbol.toStringTag]: "GeneratorFunction"; } interface GeneratorFunctionConstructor { @@ -4530,7 +4530,7 @@ interface Math { */ cbrt(x: number): number; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "Math"; } interface Date { @@ -4647,7 +4647,7 @@ interface Map { size: number; values(): IterableIterator; [Symbol.iterator]():IterableIterator<[K,V]>; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "Map"; } interface MapConstructor { @@ -4664,7 +4664,7 @@ interface WeakMap { get(key: K): V; has(key: K): boolean; set(key: K, value?: V): WeakMap; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "WeakMap"; } interface WeakMapConstructor { @@ -4686,7 +4686,7 @@ interface Set { size: number; values(): IterableIterator; [Symbol.iterator]():IterableIterator; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "Set"; } interface SetConstructor { @@ -4702,7 +4702,7 @@ interface WeakSet { clear(): void; delete(value: T): boolean; has(value: T): boolean; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "WeakSet"; } interface WeakSetConstructor { @@ -4714,7 +4714,7 @@ interface WeakSetConstructor { declare var WeakSet: WeakSetConstructor; interface JSON { - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "JSON"; } /** @@ -4724,11 +4724,11 @@ interface JSON { * buffer as needed. */ interface ArrayBuffer { - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "ArrayBuffer"; } interface DataView { - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "DataView"; } /** @@ -4749,6 +4749,7 @@ interface Int8Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Int8Array"; } interface Int8ArrayConstructor { @@ -4781,6 +4782,7 @@ interface Uint8Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "UInt8Array"; } interface Uint8ArrayConstructor { @@ -4816,6 +4818,7 @@ interface Uint8ClampedArray { values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Uint8ClampedArray"; } interface Uint8ClampedArrayConstructor { @@ -4853,6 +4856,7 @@ interface Int16Array { [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Int16Array"; } interface Int16ArrayConstructor { @@ -4885,6 +4889,7 @@ interface Uint16Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Uint16Array"; } interface Uint16ArrayConstructor { @@ -4917,6 +4922,7 @@ interface Int32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Int32Array"; } interface Int32ArrayConstructor { @@ -4949,6 +4955,7 @@ interface Uint32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Uint32Array"; } interface Uint32ArrayConstructor { @@ -4981,6 +4988,7 @@ interface Float32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Float32Array"; } interface Float32ArrayConstructor { @@ -5013,6 +5021,7 @@ interface Float64Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Float64Array"; } interface Float64ArrayConstructor { @@ -5064,7 +5073,7 @@ declare namespace Reflect { function isExtensible(target: any): boolean; function ownKeys(target: any): Array; function preventExtensions(target: any): boolean; - function set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; function setPrototypeOf(target: any, proto: any): boolean; } @@ -5089,7 +5098,7 @@ interface Promise { catch(onrejected?: (reason: any) => T | PromiseLike): Promise; catch(onrejected?: (reason: any) => void): Promise; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "Promise"; } interface PromiseConstructor { @@ -5112,7 +5121,16 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - all(values: Iterable>): Promise; + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + all(values: Iterable>): Promise; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved diff --git a/lib/lib.d.ts b/lib/lib.d.ts index fd4c05da220..155d864619e 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -4362,6 +4362,7 @@ interface AudioContext extends EventTarget { destination: AudioDestinationNode; listener: AudioListener; sampleRate: number; + state: string; createAnalyser(): AnalyserNode; createBiquadFilter(): BiquadFilterNode; createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; @@ -6099,6 +6100,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string; + currentScript: HTMLScriptElement; adoptNode(source: Node): Node; captureEvents(): void; clear(): void; @@ -6814,6 +6816,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec tagName: string; id: string; className: string; + innerHTML: string; getAttribute(name?: string): string; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; @@ -7009,7 +7012,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec removeAttributeNode(oldAttr: Attr): Attr; requestFullscreen(): void; requestPointerLock(): void; - setAttribute(name?: string, value?: string): void; + setAttribute(name: string, value: string): void; setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; @@ -7018,6 +7021,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; + matches(selector: string): boolean; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -8002,7 +8006,6 @@ interface HTMLElement extends Element { title: string; blur(): void; click(): void; - contains(child: HTMLElement): boolean; dragDrop(): boolean; focus(): void; insertAdjacentElement(position: string, insertedElement: Element): Element; @@ -9552,7 +9555,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: any; + readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -10176,7 +10179,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLSelectElement; + options: HTMLCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -10209,6 +10212,7 @@ interface HTMLSelectElement extends HTMLElement { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; + selectedOptions: HTMLCollection; /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. @@ -10462,19 +10466,19 @@ interface HTMLTableElement extends HTMLElement { /** * Creates an empty caption element in the table. */ - createCaption(): HTMLElement; + createCaption(): HTMLTableCaptionElement; /** * Creates an empty tBody element in the table. */ - createTBody(): HTMLElement; + createTBody(): HTMLTableSectionElement; /** * Creates an empty tFoot element in the table. */ - createTFoot(): HTMLElement; + createTFoot(): HTMLTableSectionElement; /** * Returns the tHead element object if successful, or null otherwise. */ - createTHead(): HTMLElement; + createTHead(): HTMLTableSectionElement; /** * Deletes the caption element and its contents from the table. */ @@ -10496,7 +10500,7 @@ interface HTMLTableElement extends HTMLElement { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; } declare var HTMLTableElement: { @@ -10547,7 +10551,7 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Creates a new cell in the table row, and adds the cell to the cells collection. * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ - insertCell(index?: number): HTMLElement; + insertCell(index?: number): HTMLTableCellElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10574,7 +10578,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10963,7 +10967,7 @@ interface IDBDatabase extends EventTarget { onerror: (ev: Event) => any; version: string; close(): void; - createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: any, mode?: string): IDBTransaction; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; @@ -10988,10 +10992,11 @@ declare var IDBFactory: { } interface IDBIndex { - keyPath: string; + keyPath: string | string[]; name: string; objectStore: IDBObjectStore; unique: boolean; + multiEntry: boolean; count(key?: any): IDBRequest; get(key: any): IDBRequest; getKey(key: any): IDBRequest; @@ -11028,7 +11033,7 @@ interface IDBObjectStore { add(value: any, key?: any): IDBRequest; clear(): IDBRequest; count(key?: any): IDBRequest; - createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; delete(key: any): IDBRequest; deleteIndex(indexName: string): void; get(key: any): IDBRequest; @@ -11112,7 +11117,7 @@ declare var IDBVersionChangeEvent: { } interface ImageData { - data: number[]; + data: Uint8ClampedArray; height: number; width: number; } @@ -11910,6 +11915,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + vibrate(pattern: number | number[]): boolean; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11950,6 +11956,7 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; + contains(node: Node): boolean; ATTRIBUTE_NODE: number; CDATA_SECTION_NODE: number; COMMENT_NODE: number; @@ -16613,6 +16620,16 @@ interface XMLHttpRequestEventTarget { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface IDBObjectStoreParameters { + keyPath?: string | string[]; + autoIncrement?: boolean; +} + +interface IDBIndexParameters { + unique?: boolean; + multiEntry?: boolean; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -16648,6 +16665,15 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface HTMLTemplateElement extends HTMLElement { + content: DocumentFragment; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 69014415c15..b2ad2c73df6 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -538,6 +538,7 @@ interface AudioContext extends EventTarget { destination: AudioDestinationNode; listener: AudioListener; sampleRate: number; + state: string; createAnalyser(): AnalyserNode; createBiquadFilter(): BiquadFilterNode; createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; @@ -2275,6 +2276,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string; + currentScript: HTMLScriptElement; adoptNode(source: Node): Node; captureEvents(): void; clear(): void; @@ -2990,6 +2992,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec tagName: string; id: string; className: string; + innerHTML: string; getAttribute(name?: string): string; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; @@ -3185,7 +3188,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec removeAttributeNode(oldAttr: Attr): Attr; requestFullscreen(): void; requestPointerLock(): void; - setAttribute(name?: string, value?: string): void; + setAttribute(name: string, value: string): void; setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; @@ -3194,6 +3197,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; + matches(selector: string): boolean; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -4178,7 +4182,6 @@ interface HTMLElement extends Element { title: string; blur(): void; click(): void; - contains(child: HTMLElement): boolean; dragDrop(): boolean; focus(): void; insertAdjacentElement(position: string, insertedElement: Element): Element; @@ -5728,7 +5731,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: any; + readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -6352,7 +6355,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLSelectElement; + options: HTMLCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -6385,6 +6388,7 @@ interface HTMLSelectElement extends HTMLElement { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; + selectedOptions: HTMLCollection; /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. @@ -6638,19 +6642,19 @@ interface HTMLTableElement extends HTMLElement { /** * Creates an empty caption element in the table. */ - createCaption(): HTMLElement; + createCaption(): HTMLTableCaptionElement; /** * Creates an empty tBody element in the table. */ - createTBody(): HTMLElement; + createTBody(): HTMLTableSectionElement; /** * Creates an empty tFoot element in the table. */ - createTFoot(): HTMLElement; + createTFoot(): HTMLTableSectionElement; /** * Returns the tHead element object if successful, or null otherwise. */ - createTHead(): HTMLElement; + createTHead(): HTMLTableSectionElement; /** * Deletes the caption element and its contents from the table. */ @@ -6672,7 +6676,7 @@ interface HTMLTableElement extends HTMLElement { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; } declare var HTMLTableElement: { @@ -6723,7 +6727,7 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Creates a new cell in the table row, and adds the cell to the cells collection. * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ - insertCell(index?: number): HTMLElement; + insertCell(index?: number): HTMLTableCellElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6750,7 +6754,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7139,7 +7143,7 @@ interface IDBDatabase extends EventTarget { onerror: (ev: Event) => any; version: string; close(): void; - createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: any, mode?: string): IDBTransaction; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; @@ -7164,10 +7168,11 @@ declare var IDBFactory: { } interface IDBIndex { - keyPath: string; + keyPath: string | string[]; name: string; objectStore: IDBObjectStore; unique: boolean; + multiEntry: boolean; count(key?: any): IDBRequest; get(key: any): IDBRequest; getKey(key: any): IDBRequest; @@ -7204,7 +7209,7 @@ interface IDBObjectStore { add(value: any, key?: any): IDBRequest; clear(): IDBRequest; count(key?: any): IDBRequest; - createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; delete(key: any): IDBRequest; deleteIndex(indexName: string): void; get(key: any): IDBRequest; @@ -7288,7 +7293,7 @@ declare var IDBVersionChangeEvent: { } interface ImageData { - data: number[]; + data: Uint8ClampedArray; height: number; width: number; } @@ -8086,6 +8091,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + vibrate(pattern: number | number[]): boolean; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -8126,6 +8132,7 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; + contains(node: Node): boolean; ATTRIBUTE_NODE: number; CDATA_SECTION_NODE: number; COMMENT_NODE: number; @@ -12789,6 +12796,16 @@ interface XMLHttpRequestEventTarget { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface IDBObjectStoreParameters { + keyPath?: string | string[]; + autoIncrement?: boolean; +} + +interface IDBIndexParameters { + unique?: boolean; + multiEntry?: boolean; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -12824,6 +12841,15 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface HTMLTemplateElement extends HTMLElement { + content: DocumentFragment; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 564c302031d..ef3399ba804 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -22,7 +22,7 @@ interface Symbol { /** Returns the primitive value of the specified object. */ valueOf(): Object; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "Symbol"; } interface SymbolConstructor { @@ -580,7 +580,7 @@ interface IterableIterator extends Iterator { } interface GeneratorFunction extends Function { - + [Symbol.toStringTag]: "GeneratorFunction"; } interface GeneratorFunctionConstructor { @@ -705,7 +705,7 @@ interface Math { */ cbrt(x: number): number; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "Math"; } interface Date { @@ -822,7 +822,7 @@ interface Map { size: number; values(): IterableIterator; [Symbol.iterator]():IterableIterator<[K,V]>; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "Map"; } interface MapConstructor { @@ -839,7 +839,7 @@ interface WeakMap { get(key: K): V; has(key: K): boolean; set(key: K, value?: V): WeakMap; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "WeakMap"; } interface WeakMapConstructor { @@ -861,7 +861,7 @@ interface Set { size: number; values(): IterableIterator; [Symbol.iterator]():IterableIterator; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "Set"; } interface SetConstructor { @@ -877,7 +877,7 @@ interface WeakSet { clear(): void; delete(value: T): boolean; has(value: T): boolean; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "WeakSet"; } interface WeakSetConstructor { @@ -889,7 +889,7 @@ interface WeakSetConstructor { declare var WeakSet: WeakSetConstructor; interface JSON { - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "JSON"; } /** @@ -899,11 +899,11 @@ interface JSON { * buffer as needed. */ interface ArrayBuffer { - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "ArrayBuffer"; } interface DataView { - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "DataView"; } /** @@ -924,6 +924,7 @@ interface Int8Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Int8Array"; } interface Int8ArrayConstructor { @@ -956,6 +957,7 @@ interface Uint8Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "UInt8Array"; } interface Uint8ArrayConstructor { @@ -991,6 +993,7 @@ interface Uint8ClampedArray { values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Uint8ClampedArray"; } interface Uint8ClampedArrayConstructor { @@ -1028,6 +1031,7 @@ interface Int16Array { [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Int16Array"; } interface Int16ArrayConstructor { @@ -1060,6 +1064,7 @@ interface Uint16Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Uint16Array"; } interface Uint16ArrayConstructor { @@ -1092,6 +1097,7 @@ interface Int32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Int32Array"; } interface Int32ArrayConstructor { @@ -1124,6 +1130,7 @@ interface Uint32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Uint32Array"; } interface Uint32ArrayConstructor { @@ -1156,6 +1163,7 @@ interface Float32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Float32Array"; } interface Float32ArrayConstructor { @@ -1188,6 +1196,7 @@ interface Float64Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: "Float64Array"; } interface Float64ArrayConstructor { @@ -1239,7 +1248,7 @@ declare namespace Reflect { function isExtensible(target: any): boolean; function ownKeys(target: any): Array; function preventExtensions(target: any): boolean; - function set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; function setPrototypeOf(target: any, proto: any): boolean; } @@ -1264,7 +1273,7 @@ interface Promise { catch(onrejected?: (reason: any) => T | PromiseLike): Promise; catch(onrejected?: (reason: any) => void): Promise; - [Symbol.toStringTag]: string; + [Symbol.toStringTag]: "Promise"; } interface PromiseConstructor { @@ -1287,7 +1296,16 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - all(values: Iterable>): Promise; + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + all(values: Iterable>): Promise; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved @@ -5677,6 +5695,7 @@ interface AudioContext extends EventTarget { destination: AudioDestinationNode; listener: AudioListener; sampleRate: number; + state: string; createAnalyser(): AnalyserNode; createBiquadFilter(): BiquadFilterNode; createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; @@ -7414,6 +7433,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string; + currentScript: HTMLScriptElement; adoptNode(source: Node): Node; captureEvents(): void; clear(): void; @@ -8129,6 +8149,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec tagName: string; id: string; className: string; + innerHTML: string; getAttribute(name?: string): string; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; @@ -8324,7 +8345,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec removeAttributeNode(oldAttr: Attr): Attr; requestFullscreen(): void; requestPointerLock(): void; - setAttribute(name?: string, value?: string): void; + setAttribute(name: string, value: string): void; setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; @@ -8333,6 +8354,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; + matches(selector: string): boolean; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -9317,7 +9339,6 @@ interface HTMLElement extends Element { title: string; blur(): void; click(): void; - contains(child: HTMLElement): boolean; dragDrop(): boolean; focus(): void; insertAdjacentElement(position: string, insertedElement: Element): Element; @@ -10867,7 +10888,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: any; + readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -11491,7 +11512,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLSelectElement; + options: HTMLCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -11524,6 +11545,7 @@ interface HTMLSelectElement extends HTMLElement { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; + selectedOptions: HTMLCollection; /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. @@ -11777,19 +11799,19 @@ interface HTMLTableElement extends HTMLElement { /** * Creates an empty caption element in the table. */ - createCaption(): HTMLElement; + createCaption(): HTMLTableCaptionElement; /** * Creates an empty tBody element in the table. */ - createTBody(): HTMLElement; + createTBody(): HTMLTableSectionElement; /** * Creates an empty tFoot element in the table. */ - createTFoot(): HTMLElement; + createTFoot(): HTMLTableSectionElement; /** * Returns the tHead element object if successful, or null otherwise. */ - createTHead(): HTMLElement; + createTHead(): HTMLTableSectionElement; /** * Deletes the caption element and its contents from the table. */ @@ -11811,7 +11833,7 @@ interface HTMLTableElement extends HTMLElement { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; } declare var HTMLTableElement: { @@ -11862,7 +11884,7 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Creates a new cell in the table row, and adds the cell to the cells collection. * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ - insertCell(index?: number): HTMLElement; + insertCell(index?: number): HTMLTableCellElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11889,7 +11911,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -12278,7 +12300,7 @@ interface IDBDatabase extends EventTarget { onerror: (ev: Event) => any; version: string; close(): void; - createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: any, mode?: string): IDBTransaction; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; @@ -12303,10 +12325,11 @@ declare var IDBFactory: { } interface IDBIndex { - keyPath: string; + keyPath: string | string[]; name: string; objectStore: IDBObjectStore; unique: boolean; + multiEntry: boolean; count(key?: any): IDBRequest; get(key: any): IDBRequest; getKey(key: any): IDBRequest; @@ -12343,7 +12366,7 @@ interface IDBObjectStore { add(value: any, key?: any): IDBRequest; clear(): IDBRequest; count(key?: any): IDBRequest; - createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; delete(key: any): IDBRequest; deleteIndex(indexName: string): void; get(key: any): IDBRequest; @@ -12427,7 +12450,7 @@ declare var IDBVersionChangeEvent: { } interface ImageData { - data: number[]; + data: Uint8ClampedArray; height: number; width: number; } @@ -13225,6 +13248,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + vibrate(pattern: number | number[]): boolean; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13265,6 +13289,7 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; + contains(node: Node): boolean; ATTRIBUTE_NODE: number; CDATA_SECTION_NODE: number; COMMENT_NODE: number; @@ -17928,6 +17953,16 @@ interface XMLHttpRequestEventTarget { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface IDBObjectStoreParameters { + keyPath?: string | string[]; + autoIncrement?: boolean; +} + +interface IDBIndexParameters { + unique?: boolean; + multiEntry?: boolean; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -17963,6 +17998,15 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface HTMLTemplateElement extends HTMLElement { + content: DocumentFragment; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 7ce06a6b4ac..1138538a1b8 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -528,7 +528,7 @@ interface IDBDatabase extends EventTarget { onerror: (ev: Event) => any; version: string; close(): void; - createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; transaction(storeNames: any, mode?: string): IDBTransaction; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; @@ -553,10 +553,11 @@ declare var IDBFactory: { } interface IDBIndex { - keyPath: string; + keyPath: string | string[]; name: string; objectStore: IDBObjectStore; unique: boolean; + multiEntry: boolean; count(key?: any): IDBRequest; get(key: any): IDBRequest; getKey(key: any): IDBRequest; @@ -593,7 +594,7 @@ interface IDBObjectStore { add(value: any, key?: any): IDBRequest; clear(): IDBRequest; count(key?: any): IDBRequest; - createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; delete(key: any): IDBRequest; deleteIndex(indexName: string): void; get(key: any): IDBRequest; @@ -677,7 +678,7 @@ declare var IDBVersionChangeEvent: { } interface ImageData { - data: number[]; + data: Uint8ClampedArray; height: number; width: number; } @@ -1109,6 +1110,16 @@ interface WorkerUtils extends Object, WindowBase64 { setTimeout(handler: any, timeout?: any, ...args: any[]): number; } +interface IDBObjectStoreParameters { + keyPath?: string | string[]; + autoIncrement?: boolean; +} + +interface IDBIndexParameters { + unique?: boolean; + multiEntry?: boolean; +} + interface BlobPropertyBag { type?: string; endings?: string; diff --git a/lib/tsc.js b/lib/tsc.js index 87a413af729..543deadb433 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -247,9 +247,11 @@ var ts; var count = array.length; if (count > 0) { var pos = 0; - var result = arguments.length <= 2 ? array[pos++] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos++; while (pos < count) { - result = f(result, array[pos++]); + result = f(result, array[pos]); + pos++; } return result; } @@ -261,9 +263,11 @@ var ts; if (array) { var pos = array.length - 1; if (pos >= 0) { - var result = arguments.length <= 2 ? array[pos--] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos--; while (pos >= 0) { - result = f(result, array[pos--]); + result = f(result, array[pos]); + pos--; } return result; } @@ -346,6 +350,22 @@ var ts; 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; + } + ts.isArray = isArray; function memoize(callback) { var value; return function () { @@ -639,7 +659,7 @@ var ts; } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; function getBaseFileName(path) { - if (!path) { + if (path === undefined) { return undefined; } var i = path.lastIndexOf(ts.directorySeparator); @@ -664,14 +684,19 @@ var ts; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; - ts.supportedExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedJsExtensions = ts.supportedExtensions.concat(".js", ".jsx"); - function isSupportedSourceFileName(fileName) { + ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedJavascriptExtensions = [".js", ".jsx"]; + var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + function getSupportedExtensions(options) { + return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + ts.getSupportedExtensions = getSupportedExtensions; + function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; } - for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; + for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -690,22 +715,6 @@ var ts; return path; } ts.removeFileExtension = removeFileExtension; - var backslashOrDoubleQuote = /[\"\\]/g; - var escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { - "\0": "\\0", - "\t": "\\t", - "\v": "\\v", - "\f": "\\f", - "\b": "\\b", - "\r": "\\r", - "\n": "\\n", - "\\": "\\\\", - "\"": "\\\"", - "\u2028": "\\u2028", - "\u2029": "\\u2029", - "\u0085": "\\u0085" - }; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -902,7 +911,6 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); - var _tty = require("tty"); function createWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } if (chunkSize === void 0) { chunkSize = 30; } @@ -970,9 +978,6 @@ var ts; }; } var watchedFileSet = createWatchedFileSet(); - function isNode4OrLater() { - return parseInt(process.version.charAt(1)) >= 4; - } var platform = _os.platform(); var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; function readFile(fileName, encoding) { @@ -1055,9 +1060,6 @@ var ts; readFile: readFile, writeFile: writeFile, watchFile: function (fileName, callback) { - if (isNode4OrLater()) { - return _fs.watch(fileName, function (eventName, relativeFileName) { return callback(fileName); }); - } var watchedFile = watchedFileSet.addFile(fileName, callback); return { close: function () { return watchedFileSet.removeFile(watchedFile); } @@ -1103,12 +1105,40 @@ var ts; } }; } + function getChakraSystem() { + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, encoding) { + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + if (writeByteOrderMark) { + data = "\uFEFF" + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + readDirectory: ChakraHost.readDirectory, + exit: ChakraHost.quit + }; + } if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { return getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { return getNodeSystem(); } + else if (typeof ChakraHost !== "undefined") { + return getChakraSystem(); + } else { return undefined; } @@ -1226,7 +1256,7 @@ var ts; Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: ts.DiagnosticCategory.Error, key: "Modifiers_not_permitted_on_index_signature_members_1145", message: "Modifiers not permitted on index signature members." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_1148", message: "Cannot compile modules unless the '--module' flag is provided." }, + Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_optio_1148", message: "Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -1313,6 +1343,10 @@ var ts; _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, + An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, + A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, + A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, @@ -1326,11 +1360,12 @@ var ts; Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list_2313", message: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." }, + Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, @@ -1340,6 +1375,7 @@ var ts; Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, + Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, @@ -1410,6 +1446,7 @@ var ts; Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, + Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, @@ -1523,6 +1560,8 @@ var ts; Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, + A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_return_type_positions_for_functions_and_methods: { code: 2519, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_r_2519", message: "A 'this'-based type predicate is only allowed within a class or interface's members, get accessors, or return type positions for functions and methods." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, @@ -1532,7 +1571,7 @@ var ts; A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_must_be_an_object_type_2600", message: "JSX element attributes type '{0}' must be an object type." }, + 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." }, Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'" }, @@ -1548,6 +1587,9 @@ var ts; Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element" }, + Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'" }, + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, 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}'." }, @@ -1632,6 +1674,11 @@ var ts; Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, + Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'" }, + The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'" }, + Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalide value for '--reactNamespace'. '{0}' is not a valid identifier." }, 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." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -1642,6 +1689,7 @@ var ts; Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -1697,6 +1745,8 @@ var ts; Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, + Allow_javascript_files_to_be_compiled: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6083", message: "Allow javascript files to be compiled." }, + Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit_6084", message: "Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit" }, 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." }, @@ -1744,7 +1794,8 @@ var ts; Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'" }, An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." } + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, + JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." } }; })(ts || (ts = {})); var ts; @@ -1934,7 +1985,8 @@ var ts; var pos = 0; var lineStart = 0; while (pos < text.length) { - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 13: if (text.charCodeAt(pos) === 10) { @@ -2037,6 +2089,9 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; function skipTrivia(text, pos, stopAfterLineBreak) { + if (!(pos >= 0)) { + return pos; + } while (true) { var ch = text.charCodeAt(pos); switch (ch) { @@ -2254,6 +2309,18 @@ var ts; ch > 127 && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; + function isIdentifier(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1, n = name.length; i < n; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifier = isIdentifier; function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0; } var pos; @@ -2363,7 +2430,8 @@ var ts; return value; } function scanString() { - var quote = text.charCodeAt(pos++); + var quote = text.charCodeAt(pos); + pos++; var result = ""; var start = pos; while (true) { @@ -2450,7 +2518,8 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); return ""; } - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 48: return "\0"; @@ -2659,7 +2728,8 @@ var ts; } return pos += 2, token = 31; } - return pos++, token = 49; + pos++; + return token = 49; case 34: case 39: tokenValue = scanString(); @@ -2670,7 +2740,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 62; } - return pos++, token = 40; + pos++; + return token = 40; case 38: if (text.charCodeAt(pos + 1) === 38) { return pos += 2, token = 51; @@ -2678,11 +2749,14 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 66; } - return pos++, token = 46; + pos++; + return token = 46; case 40: - return pos++, token = 17; + pos++; + return token = 17; case 41: - return pos++, token = 18; + pos++; + return token = 18; case 42: if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 59; @@ -2693,7 +2767,8 @@ var ts; } return pos += 2, token = 38; } - return pos++, token = 37; + pos++; + return token = 37; case 43: if (text.charCodeAt(pos + 1) === 43) { return pos += 2, token = 41; @@ -2701,9 +2776,11 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 57; } - return pos++, token = 35; + pos++; + return token = 35; case 44: - return pos++, token = 24; + pos++; + return token = 24; case 45: if (text.charCodeAt(pos + 1) === 45) { return pos += 2, token = 42; @@ -2711,7 +2788,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 58; } - return pos++, token = 36; + pos++; + return token = 36; case 46: if (isDigit(text.charCodeAt(pos + 1))) { tokenValue = scanNumber(); @@ -2720,7 +2798,8 @@ var ts; if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) { return pos += 3, token = 22; } - return pos++, token = 21; + pos++; + return token = 21; case 47: if (text.charCodeAt(pos + 1) === 47) { pos += 2; @@ -2766,7 +2845,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 61; } - return pos++, token = 39; + pos++; + return token = 39; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; @@ -2814,9 +2894,11 @@ var ts; tokenValue = scanNumber(); return token = 8; case 58: - return pos++, token = 54; + pos++; + return token = 54; case 59: - return pos++, token = 23; + pos++; + return token = 23; case 60: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2841,7 +2923,8 @@ var ts; text.charCodeAt(pos + 2) !== 42) { return pos += 2, token = 26; } - return pos++, token = 25; + pos++; + return token = 25; case 61: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2861,7 +2944,8 @@ var ts; if (text.charCodeAt(pos + 1) === 62) { return pos += 2, token = 34; } - return pos++, token = 56; + pos++; + return token = 56; case 62: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2872,20 +2956,26 @@ var ts; return token = 7; } } - return pos++, token = 27; + pos++; + return token = 27; case 63: - return pos++, token = 53; + pos++; + return token = 53; case 91: - return pos++, token = 19; + pos++; + return token = 19; case 93: - return pos++, token = 20; + pos++; + return token = 20; case 94: if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 68; } - return pos++, token = 48; + pos++; + return token = 48; case 123: - return pos++, token = 15; + pos++; + return token = 15; case 124: if (text.charCodeAt(pos + 1) === 124) { return pos += 2, token = 52; @@ -2893,13 +2983,17 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 67; } - return pos++, token = 47; + pos++; + return token = 47; case 125: - return pos++, token = 16; + pos++; + return token = 16; case 126: - return pos++, token = 50; + pos++; + return token = 50; case 64: - return pos++, token = 55; + pos++; + return token = 55; case 92: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -2908,7 +3002,8 @@ var ts; return token = getIdentifierToken(); } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0; + pos++; + return token = 0; default: if (isIdentifierStart(ch, languageVersion)) { pos++; @@ -2930,7 +3025,8 @@ var ts; continue; } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0; + pos++; + return token = 0; } } } @@ -2946,10 +3042,12 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 64; } - return pos++, token = 44; + pos++; + return token = 44; } if (text.charCodeAt(pos) === 61) { - return pos++, token = 29; + pos++; + return token = 29; } } return token; @@ -3032,7 +3130,7 @@ var ts; break; } } - return token = 236; + return token = 238; } function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { @@ -3158,7 +3256,7 @@ var ts; if (array1.length !== array2.length) { return false; } - for (var i = 0; i < array1.length; ++i) { + for (var i = 0; i < array1.length; i++) { var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; if (!equals) { return false; @@ -3198,7 +3296,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 248) { + while (node && node.kind !== 250) { node = node.parent; } return node; @@ -3289,15 +3387,15 @@ var ts; return current; } switch (current.kind) { - case 248: + case 250: + case 222: + case 246: case 220: - case 244: - case 218: - case 199: - case 200: case 201: + case 202: + case 203: return current; - case 192: + case 194: if (!isFunctionLike(current.parent)) { return current; } @@ -3308,9 +3406,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 211 && + declaration.kind === 213 && declaration.parent && - declaration.parent.kind === 244; + declaration.parent.kind === 246; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; function declarationNameToString(name) { @@ -3346,22 +3444,23 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 248: + case 250: var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); if (pos_1 === sourceFile.text.length) { return ts.createTextSpan(0, 0); } return getSpanOfTokenAtPosition(sourceFile, pos_1); - case 211: - case 163: - case 214: - case 186: - case 215: - case 218: - case 217: - case 247: case 213: - case 173: + case 165: + case 216: + case 188: + case 217: + case 220: + case 219: + case 249: + case 215: + case 175: + case 143: errorNode = node.name; break; } @@ -3387,11 +3486,11 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 217 && isConst(node); + return node.kind === 219 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 163 || isBindingPattern(node))) { + while (node && (node.kind === 165 || isBindingPattern(node))) { node = node.parent; } return node; @@ -3399,14 +3498,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 211) { + if (node.kind === 213) { node = node.parent; } - if (node && node.kind === 212) { + if (node && node.kind === 214) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 193) { + if (node && node.kind === 195) { flags |= node.flags; } return flags; @@ -3421,7 +3520,7 @@ var ts; } ts.isLet = isLet; function isPrologueDirective(node) { - return node.kind === 195 && node.expression.kind === 9; + return node.kind === 197 && node.expression.kind === 9; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { @@ -3451,7 +3550,7 @@ var ts; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isTypeNode(node) { - if (151 <= node.kind && node.kind <= 160) { + if (150 <= node.kind && node.kind <= 162) { return true; } switch (node.kind) { @@ -3462,42 +3561,40 @@ var ts; case 131: return true; case 103: - return node.parent.kind !== 177; - case 9: - return node.parent.kind === 138; - case 188: + return node.parent.kind !== 179; + case 190: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); case 69: if (node.parent.kind === 135 && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 166 && node.parent.name === node) { + else if (node.parent.kind === 168 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 69 || node.kind === 135 || node.kind === 166, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + ts.Debug.assert(node.kind === 69 || node.kind === 135 || node.kind === 168, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); case 135: - case 166: + case 168: case 97: var parent_1 = node.parent; if (parent_1.kind === 154) { return false; } - if (151 <= parent_1.kind && parent_1.kind <= 160) { + if (150 <= parent_1.kind && parent_1.kind <= 162) { return true; } switch (parent_1.kind) { - case 188: + case 190: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); case 137: return node === parent_1.constraint; case 141: case 140: case 138: - case 211: - return node === parent_1.type; case 213: - case 173: - case 174: + return node === parent_1.type; + case 215: + case 175: + case 176: case 144: case 143: case 142: @@ -3508,12 +3605,12 @@ var ts; case 148: case 149: return node === parent_1.type; - case 171: + case 173: return node === parent_1.type; - case 168: - case 169: - return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; case 170: + case 171: + return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + case 172: return false; } } @@ -3524,23 +3621,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 204: + case 206: return visitor(node); - case 220: - case 192: - case 196: - case 197: + case 222: + case 194: case 198: case 199: case 200: case 201: - case 205: - case 206: - case 241: - case 242: + case 202: + case 203: case 207: - case 209: + case 208: + case 243: case 244: + case 209: + case 211: + case 246: return ts.forEachChild(node, traverse); } } @@ -3550,18 +3647,18 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 184: + case 186: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } + case 219: case 217: - case 215: + case 220: case 218: case 216: - case 214: - case 186: + case 188: return; default: if (isFunctionLike(node)) { @@ -3581,14 +3678,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 163: - case 247: + case 165: + case 249: case 138: - case 245: + case 247: case 141: case 140: - case 246: - case 211: + case 248: + case 213: return true; } } @@ -3600,7 +3697,7 @@ var ts; } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 214 || node.kind === 186); + return node && (node.kind === 216 || node.kind === 188); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -3610,9 +3707,9 @@ var ts; function isFunctionLikeKind(kind) { switch (kind) { case 144: - case 173: - case 213: - case 174: + case 175: + case 215: + case 176: case 143: case 142: case 145: @@ -3633,8 +3730,8 @@ var ts; case 144: case 145: case 146: - case 213: - case 173: + case 215: + case 175: return true; } return false; @@ -3642,26 +3739,30 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { + case 201: + case 202: + case 203: case 199: case 200: - case 201: - case 197: - case 198: return true; - case 207: + case 209: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 192 && isFunctionLike(node.parent); + return node && node.kind === 194 && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 143 && node.parent.kind === 165; + return node && node.kind === 143 && node.parent.kind === 167; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; function getContainingFunction(node) { while (true) { node = node.parent; @@ -3701,13 +3802,13 @@ var ts; node = node.parent; } break; - case 174: + case 176: if (!includeArrowFunctions) { continue; } - case 213: - case 173: - case 218: + case 215: + case 175: + case 220: case 141: case 140: case 143: @@ -3718,37 +3819,27 @@ var ts; case 147: case 148: case 149: - case 217: - case 248: + case 219: + case 250: return node; } } } ts.getThisContainer = getThisContainer; - function getSuperContainer(node, includeFunctions) { + function getSuperContainer(node, stopOnFunctions) { while (true) { node = node.parent; - if (!node) + if (!node) { return node; + } switch (node.kind) { case 136: - if (isClassLike(node.parent.parent)) { - return node; - } node = node.parent; break; - case 139: - if (node.parent.kind === 138 && isClassElement(node.parent.parent)) { - node = node.parent.parent; - } - else if (isClassElement(node.parent)) { - node = node.parent; - } - break; - case 213: - case 173: - case 174: - if (!includeFunctions) { + case 215: + case 175: + case 176: + if (!stopOnFunctions) { continue; } case 141: @@ -3759,6 +3850,14 @@ var ts; case 145: case 146: return node; + case 139: + if (node.parent.kind === 138 && isClassElement(node.parent.parent)) { + node = node.parent.parent; + } + else if (isClassElement(node.parent)) { + node = node.parent; + } + break; } } } @@ -3768,7 +3867,7 @@ var ts; switch (node.kind) { case 151: return node.typeName; - case 188: + case 190: return node.expression; case 69: case 135: @@ -3779,7 +3878,7 @@ var ts; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 170) { + if (node.kind === 172) { return node.tag; } return node.expression; @@ -3787,23 +3886,23 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 214: + case 216: return true; case 141: - return node.parent.kind === 214; + return node.parent.kind === 216; case 138: - return node.parent.body && node.parent.parent.kind === 214; + return node.parent.body && node.parent.parent.kind === 216; case 145: case 146: case 143: - return node.body && node.parent.kind === 214; + return node.body && node.parent.kind === 216; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { switch (node.kind) { - case 214: + case 216: if (node.decorators) { return true; } @@ -3829,27 +3928,12 @@ var ts; return false; } ts.nodeIsDecorated = nodeIsDecorated; - function childIsDecorated(node) { - switch (node.kind) { - case 214: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 143: - case 146: - return ts.forEach(node.parameters, nodeIsDecorated); - } - return false; - } - ts.childIsDecorated = childIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); - } - ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function isPropertyAccessExpression(node) { - return node.kind === 166; + return node.kind === 168; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 167; + return node.kind === 169; } ts.isElementAccessExpression = isElementAccessExpression; function isExpression(node) { @@ -3859,34 +3943,34 @@ var ts; case 99: case 84: case 10: - case 164: - case 165: case 166: case 167: case 168: case 169: case 170: - case 189: case 171: case 172: + case 191: case 173: - case 186: case 174: - case 177: case 175: + case 188: case 176: case 179: - case 180: + case 177: + case 178: case 181: case 182: - case 185: case 183: - case 11: - case 187: - case 233: - case 234: case 184: - case 178: + case 187: + case 185: + case 11: + case 189: + case 235: + case 236: + case 186: + case 180: return true; case 135: while (node.parent.kind === 135) { @@ -3902,47 +3986,47 @@ var ts; case 97: var parent_2 = node.parent; switch (parent_2.kind) { - case 211: + case 213: case 138: case 141: case 140: + case 249: case 247: - case 245: - case 163: + case 165: return parent_2.initializer === node; - case 195: - case 196: case 197: case 198: - case 204: - case 205: - case 206: - case 241: - case 208: - case 206: - return parent_2.expression === node; case 199: + case 200: + case 206: + case 207: + case 208: + case 243: + case 210: + case 208: + return parent_2.expression === node; + case 201: var forStatement = parent_2; - return (forStatement.initializer === node && forStatement.initializer.kind !== 212) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 214) || forStatement.condition === node || forStatement.incrementor === node; - case 200: - case 201: + case 202: + case 203: var forInStatement = parent_2; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 212) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 214) || forInStatement.expression === node; - case 171: - case 189: + case 173: + case 191: return node === parent_2.expression; - case 190: + case 192: return node === parent_2.expression; case 136: return node === parent_2.expression; case 139: - case 240: - case 239: + case 242: + case 241: return true; - case 188: + case 190: return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: if (isExpression(parent_2)) { @@ -3964,7 +4048,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 && node.moduleReference.kind === 232; + return node.kind === 223 && node.moduleReference.kind === 234; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -3973,7 +4057,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 && node.moduleReference.kind !== 232; + return node.kind === 223 && node.moduleReference.kind !== 234; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -3985,43 +4069,54 @@ var ts; } ts.isInJavaScriptFile = isInJavaScriptFile; function isRequireCall(expression) { - return expression.kind === 168 && + return expression.kind === 170 && expression.expression.kind === 69 && expression.expression.text === "require" && expression.arguments.length === 1 && expression.arguments[0].kind === 9; } ts.isRequireCall = isRequireCall; - function isExportsPropertyAssignment(expression) { - return isInJavaScriptFile(expression) && - (expression.kind === 181) && - (expression.operatorToken.kind === 56) && - (expression.left.kind === 166) && - (expression.left.expression.kind === 69) && - ((expression.left.expression).text === "exports"); + function getSpecialPropertyAssignmentKind(expression) { + if (expression.kind !== 183) { + return 0; + } + var expr = expression; + if (expr.operatorToken.kind !== 56 || expr.left.kind !== 168) { + return 0; + } + var lhs = expr.left; + if (lhs.expression.kind === 69) { + var lhsId = lhs.expression; + if (lhsId.text === "exports") { + return 1; + } + else if (lhsId.text === "module" && lhs.name.text === "exports") { + return 2; + } + } + else if (lhs.expression.kind === 97) { + return 4; + } + else if (lhs.expression.kind === 168) { + var innerPropertyAccess = lhs.expression; + if (innerPropertyAccess.expression.kind === 69 && innerPropertyAccess.name.text === "prototype") { + return 3; + } + } + return 0; } - ts.isExportsPropertyAssignment = isExportsPropertyAssignment; - function isModuleExportsAssignment(expression) { - return isInJavaScriptFile(expression) && - (expression.kind === 181) && - (expression.operatorToken.kind === 56) && - (expression.left.kind === 166) && - (expression.left.expression.kind === 69) && - ((expression.left.expression).text === "module") && - (expression.left.name.text === "exports"); - } - ts.isModuleExportsAssignment = isModuleExportsAssignment; + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 222) { + if (node.kind === 224) { return node.moduleSpecifier; } - if (node.kind === 221) { + if (node.kind === 223) { var reference = node.moduleReference; - if (reference.kind === 232) { + if (reference.kind === 234) { return reference.expression; } } - if (node.kind === 228) { + if (node.kind === 230) { return node.moduleSpecifier; } } @@ -4032,8 +4127,8 @@ var ts; case 138: case 143: case 142: - case 246: - case 245: + case 248: + case 247: case 141: case 140: return node.questionToken !== undefined; @@ -4043,9 +4138,9 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 261 && + return node.kind === 263 && node.parameters.length > 0 && - node.parameters[0].type.kind === 263; + node.parameters[0].type.kind === 265; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function getJSDocTag(node, kind) { @@ -4059,15 +4154,15 @@ var ts; } } function getJSDocTypeTag(node) { - return getJSDocTag(node, 269); + return getJSDocTag(node, 271); } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 268); + return getJSDocTag(node, 270); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 270); + return getJSDocTag(node, 272); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getCorrespondingJSDocParameterTag(parameter) { @@ -4076,7 +4171,7 @@ var ts; var docComment = parameter.parent.jsDocComment; if (docComment) { return ts.forEach(docComment.tags, function (t) { - if (t.kind === 267) { + if (t.kind === 269) { var parameterTag = t; var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; if (name_6.text === parameterName) { @@ -4095,12 +4190,12 @@ var ts; function isRestParameter(node) { if (node) { if (node.parserContextFlags & 32) { - if (node.type && node.type.kind === 262) { + if (node.type && node.type.kind === 264) { return true; } var paramTag = getCorrespondingJSDocParameterTag(node); if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 262; + return paramTag.typeExpression.type.kind === 264; } } return node.dotDotDotToken !== undefined; @@ -4121,7 +4216,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 162 || node.kind === 161); + return !!node && (node.kind === 164 || node.kind === 163); } ts.isBindingPattern = isBindingPattern; function isNodeDescendentOf(node, ancestor) { @@ -4145,34 +4240,34 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 174: - case 163: - case 214: - case 186: + case 176: + case 165: + case 216: + case 188: case 144: - case 217: - case 247: - case 230: - case 213: - case 173: - case 145: - case 223: - case 221: - case 226: + case 219: + case 249: + case 232: case 215: + case 175: + case 145: + case 225: + case 223: + case 228: + case 217: case 143: case 142: - case 218: - case 224: + case 220: + case 226: case 138: - case 245: + case 247: case 141: case 140: case 146: - case 246: - case 216: + case 248: + case 218: case 137: - case 211: + case 213: return true; } return false; @@ -4180,25 +4275,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 203: - case 202: - case 210: - case 197: - case 195: - case 194: - case 200: - case 201: - case 199: - case 196: - case 207: + case 205: case 204: + case 212: + case 199: + case 197: + case 196: + case 202: + case 203: + case 201: + case 198: + case 209: case 206: case 208: - case 209: - case 193: - case 198: - case 205: - case 227: + case 210: + case 211: + case 195: + case 200: + case 207: + case 229: return true; default: return false; @@ -4225,7 +4320,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 226 || parent.kind === 230) { + if (parent.kind === 228 || parent.kind === 232) { if (parent.propertyName) { return true; } @@ -4245,9 +4340,9 @@ var ts; case 142: case 145: case 146: + case 249: case 247: - case 245: - case 166: + case 168: return parent.name === node; case 135: if (parent.right === node) { @@ -4257,22 +4352,22 @@ var ts; return parent.kind === 154; } return false; - case 163: - case 226: + case 165: + case 228: return parent.propertyName === node; - case 230: + case 232: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 221 || - node.kind === 223 && !!node.name || - node.kind === 224 || + return node.kind === 223 || + node.kind === 225 && !!node.name || node.kind === 226 || - node.kind === 230 || - node.kind === 227 && node.expression.kind === 69; + node.kind === 228 || + node.kind === 232 || + node.kind === 229 && node.expression.kind === 69; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -4405,7 +4500,7 @@ var ts; return node.kind === 69 && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; - function isModifier(token) { + function isModifierKind(token) { switch (token) { case 115: case 118: @@ -4421,39 +4516,56 @@ var ts; } return false; } - ts.isModifier = isModifier; + ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); return root.kind === 138; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 163) { + while (node.kind === 165) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 218 || n.kind === 248; + return isFunctionLike(n) || n.kind === 220 || n.kind === 250; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function cloneEntityName(node) { - if (node.kind === 69) { - var clone_1 = createSynthesizedNode(69); - clone_1.text = node.text; - return clone_1; + function cloneNode(node, location, flags, parent) { + var clone = location !== undefined + ? ts.createNode(node.kind, location.pos, location.end) + : createSynthesizedNode(node.kind); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; } - else { - var clone_2 = createSynthesizedNode(135); - clone_2.left = cloneEntityName(node.left); - clone_2.left.parent = clone_2; - clone_2.right = cloneEntityName(node.right); - clone_2.right.parent = clone_2; - return clone_2; + if (flags !== undefined) { + clone.flags = flags; } + if (parent !== undefined) { + clone.parent = parent; + } + return clone; + } + ts.cloneNode = cloneNode; + function cloneEntityName(node, parent) { + var clone = cloneNode(node, node, node.flags, parent); + if (isQualifiedName(clone)) { + var left = clone.left, right = clone.right; + clone.left = cloneEntityName(left, clone); + clone.right = cloneNode(right, right, right.flags, parent); + } + return clone; } ts.cloneEntityName = cloneEntityName; + function isQualifiedName(node) { + return node.kind === 135; + } + ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { return node.pos === -1; } @@ -4656,8 +4768,8 @@ var ts; writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, - increaseIndent: function () { return indent++; }, - decreaseIndent: function () { return indent--; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, getIndent: function () { return indent; }, getTextPos: function () { return output.length; }, getLine: function () { return lineCount + 1; }, @@ -4668,8 +4780,10 @@ var ts; } ts.createTextWriter = createTextWriter; function getExternalModuleNameFromPath(host, fileName) { - var dir = host.getCurrentDirectory(); - var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, fileName, dir, function (f) { return host.getCanonicalFileName(f); }, false); + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); return ts.removeFileExtension(relativePath); } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; @@ -4685,6 +4799,61 @@ var ts; return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return compilerOptions.module ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? 5 : 0; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + onBundledEmit(host); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + if (!isDeclarationFile(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, sourceFile.languageVariant === 1 && options.jsx === 1 ? ".jsx" : ".js"); + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitFilePath(jsFilePath, options) : undefined + }; + action(emitFileNames, [sourceFile], false); + } + function onBundledEmit(host) { + var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + (!isExternalModule(sourceFile) || + (getEmitModuleKind(options) && isExternalModule(sourceFile))); }); + if (bundledSources.length) { + var jsFilePath = options.outFile || options.out; + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: getDeclarationEmitFilePath(jsFilePath, options) + }; + action(emitFileNames, bundledSources, true); + } + } + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getDeclarationEmitFilePath(jsFilePath, options) { + return options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + } + } + ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); @@ -4693,7 +4862,7 @@ var ts; ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { - diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); }); } ts.writeFile = writeFile; @@ -4717,16 +4886,6 @@ var ts; return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; - function shouldEmitToOwnFile(sourceFile, compilerOptions) { - if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !(compilerOptions.outFile || compilerOptions.out))) { - return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); - } - return false; - } - return false; - } - ts.shouldEmitToOwnFile = shouldEmitToOwnFile; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -4926,24 +5085,24 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 166: - case 167: - case 169: case 168: - case 233: - case 234: + case 169: + case 171: case 170: - case 164: + case 235: + case 236: case 172: - case 165: - case 186: - case 173: + case 166: + case 174: + case 167: + case 188: + case 175: case 69: case 10: case 8: case 9: case 11: - case 183: + case 185: case 84: case 93: case 97: @@ -4960,7 +5119,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 188 && + return node.kind === 190 && node.parent.token === 83 && isClassLike(node.parent.parent); } @@ -4982,15 +5141,15 @@ var ts; } function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 135 && node.parent.right === node) || - (node.parent.kind === 166 && node.parent.name === node); + (node.parent.kind === 168 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 165) { + if (kind === 167) { return expression.properties.length === 0; } - if (kind === 164) { + if (kind === 166) { return expression.elements.length === 0; } return false; @@ -5001,13 +5160,9 @@ var ts; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function hasJavaScriptFileExtension(fileName) { - return ts.fileExtensionIs(fileName, ".js") || ts.fileExtensionIs(fileName, ".jsx"); + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function allowsJsxExpressions(fileName) { - return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx"); - } - ts.allowsJsxExpressions = allowsJsxExpressions; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -5037,6 +5192,39 @@ var ts; } return output; } + ts.stringify = typeof JSON !== "undefined" && JSON.stringify + ? JSON.stringify + : stringifyFallback; + function stringifyFallback(value) { + return value === undefined ? undefined : stringifyValue(value); + } + function stringifyValue(value) { + return typeof value === "string" ? "\"" + escapeString(value) + "\"" + : typeof value === "number" ? isFinite(value) ? String(value) : "null" + : typeof value === "boolean" ? value ? "true" : "false" + : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) + : "null"; + } + function cycleCheck(cb, value) { + ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); + value.__cycle = true; + var result = cb(value); + delete value.__cycle; + return result; + } + function stringifyArray(value) { + return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; + } + function stringifyElement(memo, value) { + return (memo ? memo + "," : memo) + stringifyValue(value); + } + function stringifyObject(value) { + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + } + function stringifyProperty(memo, value, key) { + return value === undefined || typeof value === "function" || key === "__cycle" ? memo + : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); + } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; function convertToBase64(input) { var result = ""; @@ -5207,13 +5395,17 @@ var ts; function getTypeParameterOwner(d) { if (d && d.kind === 137) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 215) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 217) { return current; } } } } ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return node.flags & 56 && node.parent.kind === 144 && ts.isClassLike(node.parent.parent); + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; })(ts || (ts = {})); var ts; (function (ts) { @@ -5221,7 +5413,7 @@ var ts; var NodeConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 248) { + if (kind === 250) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else { @@ -5264,7 +5456,7 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 246: + case 248: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -5274,9 +5466,9 @@ var ts; case 138: case 141: case 140: - case 245: - case 211: - case 163: + case 247: + case 213: + case 165: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -5300,9 +5492,9 @@ var ts; case 144: case 145: case 146: - case 173: - case 213: - case 174: + case 175: + case 215: + case 176: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -5332,271 +5524,271 @@ var ts; return visitNodes(cbNodes, node.types); case 160: return visitNode(cbNode, node.type); - case 161: - case 162: - return visitNodes(cbNodes, node.elements); + case 163: case 164: return visitNodes(cbNodes, node.elements); - case 165: - return visitNodes(cbNodes, node.properties); case 166: + return visitNodes(cbNodes, node.elements); + case 167: + return visitNodes(cbNodes, node.properties); + case 168: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 167: + case 169: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 168: - case 169: + case 170: + case 171: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 170: + case 172: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 171: + case 173: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 172: - return visitNode(cbNode, node.expression); - case 175: - return visitNode(cbNode, node.expression); - case 176: + case 174: return visitNode(cbNode, node.expression); case 177: return visitNode(cbNode, node.expression); - case 179: - return visitNode(cbNode, node.operand); - case 184: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); case 178: return visitNode(cbNode, node.expression); - case 180: - return visitNode(cbNode, node.operand); + case 179: + return visitNode(cbNode, node.expression); case 181: + return visitNode(cbNode, node.operand); + case 186: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 180: + return visitNode(cbNode, node.expression); + case 182: + return visitNode(cbNode, node.operand); + case 183: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 189: + case 191: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 182: + case 184: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 185: + case 187: return visitNode(cbNode, node.expression); - case 192: - case 219: + case 194: + case 221: return visitNodes(cbNodes, node.statements); - case 248: + case 250: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 193: + case 195: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 212: + case 214: return visitNodes(cbNodes, node.declarations); - case 195: + case 197: return visitNode(cbNode, node.expression); - case 196: + case 198: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 197: + case 199: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 198: + case 200: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 199: + case 201: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 200: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 201: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); case 202: - case 203: - return visitNode(cbNode, node.label); - case 204: - return visitNode(cbNode, node.expression); - case 205: - return visitNode(cbNode, node.expression) || + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); + case 203: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 204: + case 205: + return visitNode(cbNode, node.label); case 206: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 220: - return visitNodes(cbNodes, node.clauses); - case 241: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.statements); - case 242: - return visitNodes(cbNodes, node.statements); + return visitNode(cbNode, node.expression); case 207: - return visitNode(cbNode, node.label) || + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); case 208: - return visitNode(cbNode, node.expression); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 222: + return visitNodes(cbNodes, node.clauses); + case 243: + return visitNode(cbNode, node.expression) || + visitNodes(cbNodes, node.statements); + case 244: + return visitNodes(cbNodes, node.statements); case 209: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 210: + return visitNode(cbNode, node.expression); + case 211: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 244: + case 246: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); case 139: return visitNode(cbNode, node.expression); - case 214: - case 186: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 215: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); case 216: + case 188: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || - visitNode(cbNode, node.type); + visitNodes(cbNodes, node.heritageClauses) || + visitNodes(cbNodes, node.members); case 217: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeParameters) || + visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 247: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); case 218: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 219: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.members); + case 249: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 220: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 221: + case 223: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 222: + case 224: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 223: + case 225: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 224: + case 226: return visitNode(cbNode, node.name); - case 225: - case 229: + case 227: + case 231: return visitNodes(cbNodes, node.elements); - case 228: + case 230: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 226: - case 230: + case 228: + case 232: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 227: + case 229: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 183: + case 185: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 190: + case 192: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); case 136: return visitNode(cbNode, node.expression); - case 243: + case 245: return visitNodes(cbNodes, node.types); - case 188: + case 190: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 232: + case 234: return visitNode(cbNode, node.expression); - case 231: - return visitNodes(cbNodes, node.decorators); case 233: + return visitNodes(cbNodes, node.decorators); + case 235: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 234: - case 235: + case 236: + case 237: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 238: + case 240: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); + case 241: + return visitNode(cbNode, node.expression); + case 242: + return visitNode(cbNode, node.expression); case 239: - return visitNode(cbNode, node.expression); - case 240: - return visitNode(cbNode, node.expression); - case 237: return visitNode(cbNode, node.tagName); - case 249: - return visitNode(cbNode, node.type); - case 253: - return visitNodes(cbNodes, node.types); - case 254: - return visitNodes(cbNodes, node.types); - case 252: - return visitNode(cbNode, node.elementType); - case 256: + case 251: return visitNode(cbNode, node.type); case 255: + return visitNodes(cbNodes, node.types); + case 256: + return visitNodes(cbNodes, node.types); + case 254: + return visitNode(cbNode, node.elementType); + case 258: return visitNode(cbNode, node.type); case 257: - return visitNodes(cbNodes, node.members); + return visitNode(cbNode, node.type); case 259: + return visitNodes(cbNodes, node.members); + case 261: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); - case 260: - return visitNode(cbNode, node.type); - case 261: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); case 262: return visitNode(cbNode, node.type); case 263: - return visitNode(cbNode, node.type); + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 264: return visitNode(cbNode, node.type); - case 258: + case 265: + return visitNode(cbNode, node.type); + case 266: + return visitNode(cbNode, node.type); + case 260: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 265: - return visitNodes(cbNodes, node.tags); case 267: + return visitNodes(cbNodes, node.tags); + case 269: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 268: - return visitNode(cbNode, node.typeExpression); - case 269: - return visitNode(cbNode, node.typeExpression); case 270: + return visitNode(cbNode, node.typeExpression); + case 271: + return visitNode(cbNode, node.typeExpression); + case 272: return visitNodes(cbNodes, node.typeParameters); } } @@ -5646,6 +5838,9 @@ var ts; return result; } Parser.parseSourceFile = parseSourceFile; + function getLanguageVariant(fileName) { + return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx") ? 1 : 0; + } function initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); @@ -5661,7 +5856,7 @@ var ts; scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(ts.allowsJsxExpressions(fileName) ? 1 : 0); + scanner.setLanguageVariant(getLanguageVariant(fileName)); } function clearState() { scanner.setText(""); @@ -5700,8 +5895,8 @@ var ts; return; function visit(node) { switch (node.kind) { - case 193: - case 213: + case 195: + case 215: case 138: addJSDocComment(node); } @@ -5736,14 +5931,14 @@ var ts; } Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion) { - var sourceFile = new SourceFileConstructor(248, 0, sourceText.length); + var sourceFile = new SourceFileConstructor(250, 0, sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 : 0; - sourceFile.languageVariant = ts.allowsJsxExpressions(sourceFile.fileName) ? 1 : 0; + sourceFile.languageVariant = getLanguageVariant(sourceFile.fileName); return sourceFile; } function setContextFlag(val, flag) { @@ -5795,9 +5990,6 @@ var ts; function doInYieldContext(func) { return doInsideOfContext(2, func); } - function doOutsideOfYieldContext(func) { - return doOutsideOfContext(2, func); - } function doInDecoratorContext(func) { return doInsideOfContext(4, func); } @@ -5810,9 +6002,6 @@ var ts; function doInYieldAndAwaitContext(func) { return doInsideOfContext(2 | 8, func); } - function doOutsideOfYieldAndAwaitContext(func) { - return doOutsideOfContext(2 | 8, func); - } function inContext(flags) { return (contextFlags & flags) !== 0; } @@ -5853,9 +6042,6 @@ var ts; function nextToken() { return token = scanner.scan(); } - function getTokenPos(pos) { - return ts.skipTrivia(sourceText, pos); - } function reScanGreaterToken() { return token = scanner.reScanGreaterToken(); } @@ -6045,6 +6231,13 @@ var ts; function parseContextualModifier(t) { return token === t && tryParse(nextTokenCanFollowModifier); } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } function nextTokenCanFollowModifier() { if (token === 74) { return nextToken() === 81; @@ -6063,14 +6256,10 @@ var ts; nextToken(); return canFollowModifier(); } - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); + return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifier(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { return token === 19 @@ -6337,7 +6526,7 @@ var ts; case 145: case 146: case 141: - case 191: + case 193: return true; case 143: var methodDeclaration = node; @@ -6351,8 +6540,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 241: - case 242: + case 243: + case 244: return true; } } @@ -6361,42 +6550,42 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 213: - case 193: - case 192: - case 196: + case 215: case 195: - case 208: - case 204: - case 206: - case 203: - case 202: - case 200: - case 201: - case 199: - case 198: - case 205: case 194: - case 209: - case 207: + case 198: case 197: case 210: - case 222: - case 221: - case 228: - case 227: - case 218: - case 214: - case 215: - case 217: + case 206: + case 208: + case 205: + case 204: + case 202: + case 203: + case 201: + case 200: + case 207: + case 196: + case 211: + case 209: + case 199: + case 212: + case 224: + case 223: + case 230: + case 229: + case 220: case 216: + case 217: + case 219: + case 218: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 247; + return node.kind === 249; } function isReusableTypeMember(node) { if (node) { @@ -6412,7 +6601,7 @@ var ts; return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 211) { + if (node.kind !== 213) { return false; } var variableDeclarator = node; @@ -6536,8 +6725,8 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(183); - template.head = parseLiteralNode(); + var template = createNode(185); + template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); var templateSpans = []; templateSpans.pos = getNodePos(); @@ -6549,12 +6738,12 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(190); + var span = createNode(192); span.expression = allowInAnd(parseExpression); var literal; if (token === 16) { reScanTemplateToken(); - literal = parseLiteralNode(); + literal = parseTemplateLiteralFragment(); } else { literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); @@ -6562,8 +6751,17 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(162, true); + } function parseLiteralNode(internName) { - var node = createNode(token); + return parseLiteralLikeNode(token, internName); + } + function parseTemplateLiteralFragment() { + return parseLiteralLikeNode(token, false); + } + function parseLiteralLikeNode(kind, internName) { + var node = createNode(kind); var text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -6585,11 +6783,7 @@ var ts; function parseTypeReferenceOrTypePredicate() { var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); if (typeName.kind === 69 && token === 124 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var node_1 = createNode(150, typeName.pos); - node_1.parameterName = typeName; - node_1.type = parseType(); - return finishNode(node_1); + return parseTypePredicate(typeName); } var node = createNode(151, typeName.pos); node.typeName = typeName; @@ -6598,6 +6792,18 @@ var ts; } return finishNode(node); } + function parseTypePredicate(lhs) { + nextToken(); + var node = createNode(150, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(161); + nextToken(); + return finishNode(node); + } function parseTypeQuery() { var node = createNode(154); parseExpected(101); @@ -6629,7 +6835,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 || isIdentifierOrPattern() || ts.isModifier(token) || token === 55; + return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55; } function setModifiers(node, modifiers) { if (modifiers) { @@ -6643,7 +6849,7 @@ var ts; setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifier(token)) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { nextToken(); } node.questionToken = parseOptionalToken(53); @@ -6711,7 +6917,7 @@ var ts; if (token === 22 || token === 20) { return true; } - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -6758,6 +6964,9 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); + if (token === 56) { + property.initializer = parseNonParameterInitializer(); + } parseTypeMemberSemicolon(); return finishNode(property); } @@ -6769,7 +6978,7 @@ var ts; case 19: return true; default: - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { var result = lookAhead(isStartOfIndexSignatureDeclaration); if (result) { return result; @@ -6779,7 +6988,7 @@ var ts; } } function isStartOfIndexSignatureDeclaration() { - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { nextToken(); } return isIndexSignature(); @@ -6809,7 +7018,7 @@ var ts; case 8: return parsePropertyOrMethodSignature(); default: - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { var result = tryParse(parseIndexSignatureWithModifiers); if (result) { return result; @@ -6882,10 +7091,18 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReferenceOrTypePredicate(); case 9: - return parseLiteralNode(true); + return parseStringLiteralTypeNode(); case 103: - case 97: return parseTokenNode(); + case 97: { + var thisKeyword = parseThisTypeNode(); + if (token === 124 && !scanner.hasPrecedingLineBreak()) { + return parseTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } case 101: return parseTypeQuery(); case 15: @@ -6966,11 +7183,11 @@ var ts; if (token === 18 || token === 22) { return true; } - if (isIdentifier() || ts.isModifier(token)) { + if (isIdentifier() || ts.isModifierKind(token)) { nextToken(); if (token === 54 || token === 24 || token === 53 || token === 56 || - isIdentifier() || ts.isModifier(token)) { + isIdentifier() || ts.isModifierKind(token)) { return true; } if (token === 18) { @@ -7054,9 +7271,6 @@ var ts; token !== 55 && isStartOfExpression(); } - function allowInAndParseExpression() { - return allowInAnd(parseExpression); - } function parseExpression() { var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { @@ -7112,7 +7326,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(184); + var node = createNode(186); nextToken(); if (!scanner.hasPrecedingLineBreak() && (token === 37 || isStartOfExpression())) { @@ -7126,7 +7340,7 @@ var ts; } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(174, identifier.pos); + var node = createNode(176, identifier.pos); var parameter = createNode(138, identifier.pos); parameter.name = identifier; finishNode(parameter); @@ -7238,7 +7452,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(174); + var node = createNode(176); setModifiers(node, parseModifiersForArrowFunction()); var isAsync = !!(node.flags & 256); fillSignature(54, false, isAsync, !allowAmbiguity, node); @@ -7270,7 +7484,7 @@ var ts; if (!questionToken) { return leftOperand; } - var node = createNode(182, leftOperand.pos); + var node = createNode(184, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -7361,39 +7575,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(181, left.pos); + var node = createNode(183, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(189, left.pos); + var node = createNode(191, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(179); + var node = createNode(181); node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(175); + var node = createNode(177); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(176); + var node = createNode(178); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(177); + var node = createNode(179); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -7408,7 +7622,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(178); + var node = createNode(180); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -7427,7 +7641,7 @@ var ts; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === 38) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 171) { + if (simpleUnaryExpression.kind === 173) { 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); } else { @@ -7475,7 +7689,7 @@ var ts; } function parseIncrementExpression() { if (token === 41 || token === 42) { - var node = createNode(179); + var node = createNode(181); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -7487,7 +7701,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 41 || token === 42) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(180, expression.pos); + var node = createNode(182, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -7510,31 +7724,44 @@ var ts; if (token === 17 || token === 21 || token === 19) { return expression; } - var node = createNode(166, expression.pos); + var node = createNode(168, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 69) { + return lhs.text === rhs.text; + } + return lhs.right.text === rhs.right.text && + tagNamesAreEquivalent(lhs.left, rhs.left); + } function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 235) { - var node = createNode(233, opening.pos); + if (opening.kind === 237) { + var node = createNode(235, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 234); + ts.Debug.assert(opening.kind === 236); result = opening; } if (inExpressionContext && token === 25) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(181, result.pos); + var badNode = createNode(183, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -7546,13 +7773,13 @@ var ts; return result; } function parseJsxText() { - var node = createNode(236, scanner.getStartPos()); + var node = createNode(238, scanner.getStartPos()); token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token) { - case 236: + case 238: return parseJsxText(); case 15: return parseJsxExpression(false); @@ -7572,7 +7799,7 @@ var ts; break; } else if (token === 1) { - parseErrorAtCurrentToken(ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } result.push(parseJsxChild()); @@ -7588,7 +7815,7 @@ var ts; var attributes = parseList(13, parseJsxAttribute); var node; if (token === 27) { - node = createNode(235, fullStart); + node = createNode(237, fullStart); scanJsxText(); } else { @@ -7600,7 +7827,7 @@ var ts; parseExpected(27, undefined, false); scanJsxText(); } - node = createNode(234, fullStart); + node = createNode(236, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -7619,10 +7846,10 @@ var ts; return elementName; } function parseJsxExpression(inExpressionContext) { - var node = createNode(240); + var node = createNode(242); parseExpected(15); if (token !== 16) { - node.expression = parseExpression(); + node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { parseExpected(16); @@ -7638,7 +7865,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(238); + var node = createNode(240); node.name = parseIdentifierName(); if (parseOptional(56)) { switch (token) { @@ -7653,7 +7880,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(239); + var node = createNode(241); parseExpected(15); parseExpected(22); node.expression = parseExpression(); @@ -7661,7 +7888,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(237); + var node = createNode(239); parseExpected(26); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -7674,7 +7901,7 @@ var ts; return finishNode(node); } function parseTypeAssertion() { - var node = createNode(171); + var node = createNode(173); parseExpected(25); node.type = parseType(); parseExpected(27); @@ -7685,7 +7912,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(21); if (dotToken) { - var propertyAccess = createNode(166, expression.pos); + var propertyAccess = createNode(168, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); @@ -7693,7 +7920,7 @@ var ts; continue; } if (!inDecoratorContext() && parseOptional(19)) { - var indexedAccess = createNode(167, expression.pos); + var indexedAccess = createNode(169, expression.pos); indexedAccess.expression = expression; if (token !== 20) { indexedAccess.argumentExpression = allowInAnd(parseExpression); @@ -7707,7 +7934,7 @@ var ts; continue; } if (token === 11 || token === 12) { - var tagExpression = createNode(170, expression.pos); + var tagExpression = createNode(172, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 11 ? parseLiteralNode() @@ -7726,7 +7953,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(168, expression.pos); + var callExpr = createNode(170, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -7734,7 +7961,7 @@ var ts; continue; } else if (token === 17) { - var callExpr = createNode(168, expression.pos); + var callExpr = createNode(170, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -7829,28 +8056,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(172); + var node = createNode(174); parseExpected(17); node.expression = allowInAnd(parseExpression); parseExpected(18); return finishNode(node); } function parseSpreadElement() { - var node = createNode(185); + var node = createNode(187); parseExpected(22); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 22 ? parseSpreadElement() : - token === 24 ? createNode(187) : + token === 24 ? createNode(189) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(164); + var node = createNode(166); parseExpected(19); if (scanner.hasPrecedingLineBreak()) node.flags |= 1024; @@ -7877,7 +8104,6 @@ var ts; } var asteriskToken = parseOptionalToken(37); var tokenIsIdentifier = isIdentifier(); - var nameToken = token; var propertyName = parsePropertyName(); var questionToken = parseOptionalToken(53); if (asteriskToken || token === 17 || token === 25) { @@ -7885,7 +8111,7 @@ var ts; } var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 || token === 16 || token === 56); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(246, fullStart); + var shorthandDeclaration = createNode(248, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; var equalsToken = parseOptionalToken(56); @@ -7896,7 +8122,8 @@ var ts; return finishNode(shorthandDeclaration); } else { - var propertyAssignment = createNode(245, fullStart); + var propertyAssignment = createNode(247, fullStart); + propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(54); @@ -7905,7 +8132,7 @@ var ts; } } function parseObjectLiteralExpression() { - var node = createNode(165); + var node = createNode(167); parseExpected(15); if (scanner.hasPrecedingLineBreak()) { node.flags |= 1024; @@ -7919,7 +8146,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(173); + var node = createNode(175); setModifiers(node, parseModifiers()); parseExpected(87); node.asteriskToken = parseOptionalToken(37); @@ -7941,7 +8168,7 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(169); + var node = createNode(171); parseExpected(92); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -7951,7 +8178,7 @@ var ts; return finishNode(node); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(192); + var node = createNode(194); if (parseExpected(15, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(1, parseStatement); parseExpected(16); @@ -7979,12 +8206,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(194); + var node = createNode(196); parseExpected(23); return finishNode(node); } function parseIfStatement() { - var node = createNode(196); + var node = createNode(198); parseExpected(88); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -7994,7 +8221,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(197); + var node = createNode(199); parseExpected(79); node.statement = parseStatement(); parseExpected(104); @@ -8005,7 +8232,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(198); + var node = createNode(200); parseExpected(104); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -8028,21 +8255,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(90)) { - var forInStatement = createNode(200, pos); + var forInStatement = createNode(202, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(18); forOrForInOrForOfStatement = forInStatement; } else if (parseOptional(134)) { - var forOfStatement = createNode(201, pos); + var forOfStatement = createNode(203, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(18); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(199, pos); + var forStatement = createNode(201, pos); forStatement.initializer = initializer; parseExpected(23); if (token !== 23 && token !== 18) { @@ -8060,7 +8287,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 203 ? 70 : 75); + parseExpected(kind === 205 ? 70 : 75); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -8068,7 +8295,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(204); + var node = createNode(206); parseExpected(94); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -8077,7 +8304,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(205); + var node = createNode(207); parseExpected(105); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -8086,7 +8313,7 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(241); + var node = createNode(243); parseExpected(71); node.expression = allowInAnd(parseExpression); parseExpected(54); @@ -8094,7 +8321,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(242); + var node = createNode(244); parseExpected(77); parseExpected(54); node.statements = parseList(3, parseStatement); @@ -8104,12 +8331,12 @@ var ts; return token === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(206); + var node = createNode(208); parseExpected(96); parseExpected(17); node.expression = allowInAnd(parseExpression); parseExpected(18); - var caseBlock = createNode(220, scanner.getStartPos()); + var caseBlock = createNode(222, scanner.getStartPos()); parseExpected(15); caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); parseExpected(16); @@ -8117,14 +8344,14 @@ var ts; return finishNode(node); } function parseThrowStatement() { - var node = createNode(208); + var node = createNode(210); parseExpected(98); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(209); + var node = createNode(211); parseExpected(100); node.tryBlock = parseBlock(false); node.catchClause = token === 72 ? parseCatchClause() : undefined; @@ -8135,7 +8362,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(244); + var result = createNode(246); parseExpected(72); if (parseExpected(17)) { result.variableDeclaration = parseVariableDeclaration(); @@ -8145,7 +8372,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(210); + var node = createNode(212); parseExpected(76); parseSemicolon(); return finishNode(node); @@ -8154,13 +8381,13 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 69 && parseOptional(54)) { - var labeledStatement = createNode(207, fullStart); + var labeledStatement = createNode(209, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - var expressionStatement = createNode(195, fullStart); + var expressionStatement = createNode(197, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); @@ -8305,9 +8532,9 @@ var ts; case 86: return parseForOrForInOrForOfStatement(); case 75: - return parseBreakOrContinueStatement(202); + return parseBreakOrContinueStatement(204); case 70: - return parseBreakOrContinueStatement(203); + return parseBreakOrContinueStatement(205); case 94: return parseReturnStatement(); case 105: @@ -8377,7 +8604,7 @@ var ts; parseExportDeclaration(fullStart, decorators, modifiers); default: if (decorators || modifiers) { - var node = createMissingNode(231, true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(233, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; setModifiers(node, modifiers); @@ -8398,16 +8625,16 @@ var ts; } function parseArrayBindingElement() { if (token === 24) { - return createNode(187); + return createNode(189); } - var node = createNode(163); + var node = createNode(165); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(163); + var node = createNode(165); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== 54) { @@ -8422,14 +8649,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(161); + var node = createNode(163); parseExpected(15); node.elements = parseDelimitedList(9, parseObjectBindingElement); parseExpected(16); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(162); + var node = createNode(164); parseExpected(19); node.elements = parseDelimitedList(10, parseArrayBindingElement); parseExpected(20); @@ -8448,7 +8675,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(211); + var node = createNode(213); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -8457,7 +8684,7 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(212); + var node = createNode(214); switch (token) { case 102: break; @@ -8486,7 +8713,7 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 18; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(193, fullStart); + var node = createNode(195, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(false); @@ -8494,7 +8721,7 @@ var ts; return finishNode(node); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(213, fullStart); + var node = createNode(215, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(87); @@ -8580,7 +8807,7 @@ var ts; if (token === 55) { return true; } - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { idToken = token; if (isClassMemberModifier(idToken)) { return true; @@ -8623,7 +8850,7 @@ var ts; } if (!decorators) { decorators = []; - decorators.pos = scanner.getStartPos(); + decorators.pos = decoratorStart; } var decorator = createNode(139, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); @@ -8634,14 +8861,21 @@ var ts; } return decorators; } - function parseModifiers() { + function parseModifiers(permitInvalidConstAsModifier) { var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token; - if (!parseAnyContextualModifier()) { - break; + if (token === 74 && permitInvalidConstAsModifier) { + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } } if (!modifiers) { modifiers = []; @@ -8674,13 +8908,13 @@ var ts; } function parseClassElement() { if (token === 23) { - var result = createNode(191); + var result = createNode(193); nextToken(); return finishNode(result); } var fullStart = getNodePos(); var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var modifiers = parseModifiers(true); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; @@ -8705,10 +8939,10 @@ var ts; ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 186); + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 188); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 214); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 216); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); @@ -8741,12 +8975,9 @@ var ts; } return undefined; } - function parseHeritageClausesWorker() { - return parseList(20, parseHeritageClause); - } function parseHeritageClause() { if (token === 83 || token === 106) { - var node = createNode(243); + var node = createNode(245); node.token = token; nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); @@ -8755,7 +8986,7 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(188); + var node = createNode(190); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); @@ -8769,7 +9000,7 @@ var ts; return parseList(5, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(215, fullStart); + var node = createNode(217, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(107); @@ -8780,7 +9011,7 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(216, fullStart); + var node = createNode(218, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(132); @@ -8792,13 +9023,13 @@ var ts; return finishNode(node); } function parseEnumMember() { - var node = createNode(247, scanner.getStartPos()); + var node = createNode(249, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(217, fullStart); + var node = createNode(219, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(81); @@ -8813,7 +9044,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(219, scanner.getStartPos()); + var node = createNode(221, scanner.getStartPos()); if (parseExpected(15)) { node.statements = parseList(1, parseStatement); parseExpected(16); @@ -8824,7 +9055,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(218, fullStart); + var node = createNode(220, fullStart); var namespaceFlag = flags & 65536; node.decorators = decorators; setModifiers(node, modifiers); @@ -8836,7 +9067,7 @@ var ts; return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(218, fullStart); + var node = createNode(220, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parseLiteralNode(true); @@ -8866,11 +9097,6 @@ var ts; function nextTokenIsSlash() { return nextToken() === 39; } - function nextTokenIsCommaOrFromKeyword() { - nextToken(); - return token === 24 || - token === 133; - } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(89); var afterImportPos = scanner.getStartPos(); @@ -8878,7 +9104,7 @@ var ts; if (isIdentifier()) { identifier = parseIdentifier(); if (token !== 24 && token !== 133) { - var importEqualsDeclaration = createNode(221, fullStart); + var importEqualsDeclaration = createNode(223, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -8888,7 +9114,7 @@ var ts; return finishNode(importEqualsDeclaration); } } - var importDeclaration = createNode(222, fullStart); + var importDeclaration = createNode(224, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || @@ -8902,13 +9128,13 @@ var ts; return finishNode(importDeclaration); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(223, fullStart); + var importClause = createNode(225, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || parseOptional(24)) { - importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(225); + importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(227); } return finishNode(importClause); } @@ -8918,7 +9144,7 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(232); + var node = createNode(234); parseExpected(127); parseExpected(17); node.expression = parseModuleSpecifier(); @@ -8926,14 +9152,17 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - var result = parseExpression(); - if (result.kind === 9) { + if (token === 9) { + var result = parseLiteralNode(); internIdentifier(result.text); + return result; + } + else { + return parseExpression(); } - return result; } function parseNamespaceImport() { - var namespaceImport = createNode(224); + var namespaceImport = createNode(226); parseExpected(37); parseExpected(116); namespaceImport.name = parseIdentifier(); @@ -8941,14 +9170,14 @@ var ts; } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(21, kind === 225 ? parseImportSpecifier : parseExportSpecifier, 15, 16); + node.elements = parseBracketedList(21, kind === 227 ? parseImportSpecifier : parseExportSpecifier, 15, 16); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(230); + return parseImportOrExportSpecifier(232); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(226); + return parseImportOrExportSpecifier(228); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -8967,13 +9196,13 @@ var ts; else { node.name = identifierName; } - if (kind === 226 && checkIdentifierIsKeyword) { + if (kind === 228 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228, fullStart); + var node = createNode(230, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(37)) { @@ -8981,7 +9210,7 @@ var ts; node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(229); + node.exportClause = parseNamedImportsOrExports(231); if (token === 133 || (token === 9 && !scanner.hasPrecedingLineBreak())) { parseExpected(133); node.moduleSpecifier = parseModuleSpecifier(); @@ -8991,7 +9220,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(227, fullStart); + var node = createNode(229, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(56)) { @@ -9011,11 +9240,13 @@ var ts; var amdModuleName; while (true) { var kind = triviaScanner.scan(); - if (kind === 5 || kind === 4 || kind === 3) { - continue; - } if (kind !== 2) { - break; + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } } var range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; var comment = sourceText.substring(range.pos, range.end); @@ -9061,10 +9292,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return node.flags & 2 - || node.kind === 221 && node.moduleReference.kind === 232 - || node.kind === 222 - || node.kind === 227 - || node.kind === 228 + || node.kind === 223 && node.moduleReference.kind === 234 + || node.kind === 224 + || node.kind === 229 + || node.kind === 230 ? node : undefined; }); @@ -9099,7 +9330,7 @@ var ts; function parseJSDocTypeExpression(start, length) { scanner.setText(sourceText, start, length); token = nextToken(); - var result = createNode(249); + var result = createNode(251); parseExpected(15); result.type = parseJSDocTopLevelType(); parseExpected(16); @@ -9110,12 +9341,12 @@ var ts; function parseJSDocTopLevelType() { var type = parseJSDocType(); if (token === 47) { - var unionType = createNode(253, type.pos); + var unionType = createNode(255, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } if (token === 56) { - var optionalType = createNode(260, type.pos); + var optionalType = createNode(262, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -9126,20 +9357,20 @@ var ts; var type = parseBasicTypeExpression(); while (true) { if (token === 19) { - var arrayType = createNode(252, type.pos); + var arrayType = createNode(254, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20); type = finishNode(arrayType); } else if (token === 53) { - var nullableType = createNode(255, type.pos); + var nullableType = createNode(257, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } else if (token === 49) { - var nonNullableType = createNode(256, type.pos); + var nonNullableType = createNode(258, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -9183,27 +9414,27 @@ var ts; return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(264); + var result = createNode(266); nextToken(); parseExpected(54); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(263); + var result = createNode(265); nextToken(); parseExpected(54); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(262); + var result = createNode(264); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(261); + var result = createNode(263); nextToken(); parseExpected(17); result.parameters = parseDelimitedList(22, parseJSDocParameter); @@ -9220,14 +9451,8 @@ var ts; parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocOptionalType(type) { - var result = createNode(260, type.pos); - nextToken(); - result.type = type; - return finishNode(result); - } function parseJSDocTypeReference() { - var result = createNode(259); + var result = createNode(261); result.name = parseSimplePropertyName(); while (parseOptional(21)) { if (token === 25) { @@ -9262,7 +9487,7 @@ var ts; return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(257); + var result = createNode(259); nextToken(); result.members = parseDelimitedList(24, parseJSDocRecordMember); checkForTrailingComma(result.members); @@ -9270,7 +9495,7 @@ var ts; return finishNode(result); } function parseJSDocRecordMember() { - var result = createNode(258); + var result = createNode(260); result.name = parseSimplePropertyName(); if (token === 54) { nextToken(); @@ -9279,13 +9504,13 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(256); + var result = createNode(258); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(254); + var result = createNode(256); nextToken(); result.types = parseDelimitedList(25, parseJSDocType); checkForTrailingComma(result.types); @@ -9299,7 +9524,7 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(253); + var result = createNode(255); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); parseExpected(18); @@ -9317,7 +9542,7 @@ var ts; return types; } function parseJSDocAllType() { - var result = createNode(250); + var result = createNode(252); nextToken(); return finishNode(result); } @@ -9330,11 +9555,11 @@ var ts; token === 27 || token === 56 || token === 47) { - var result = createNode(251, pos); + var result = createNode(253, pos); return finishNode(result); } else { - var result = createNode(255, pos); + var result = createNode(257, pos); result.type = parseJSDocType(); return finishNode(result); } @@ -9405,7 +9630,7 @@ var ts; if (!tags) { return undefined; } - var result = createNode(265, start); + var result = createNode(267, start); result.tags = tags; return finishNode(result, end); } @@ -9442,7 +9667,7 @@ var ts; return undefined; } function handleUnknownTag(atToken, tagName) { - var result = createNode(266, atToken.pos); + var result = createNode(268, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result, pos); @@ -9493,7 +9718,7 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(267, atToken.pos); + var result = createNode(269, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; @@ -9503,27 +9728,27 @@ var ts; return finishNode(result, pos); } function handleReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 268; })) { + if (ts.forEach(tags, function (t) { return t.kind === 270; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(268, atToken.pos); + var result = createNode(270, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result, pos); } function handleTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 269; })) { + if (ts.forEach(tags, function (t) { return t.kind === 271; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(269, atToken.pos); + var result = createNode(271, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result, pos); } function handleTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 270; })) { + if (ts.forEach(tags, function (t) { return t.kind === 272; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } var typeParameters = []; @@ -9547,7 +9772,7 @@ var ts; pos++; } typeParameters.end = pos; - var result = createNode(270, atToken.pos); + var result = createNode(272, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; @@ -9869,16 +10094,16 @@ var ts; : 4; } function getModuleInstanceState(node) { - if (node.kind === 215 || node.kind === 216) { + if (node.kind === 217 || node.kind === 218) { return 0; } else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 222 || node.kind === 221) && !(node.flags & 2)) { + else if ((node.kind === 224 || node.kind === 223) && !(node.flags & 2)) { return 0; } - else if (node.kind === 219) { + else if (node.kind === 221) { var state = 0; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -9894,7 +10119,7 @@ var ts; }); return state; } - else if (node.kind === 218) { + else if (node.kind === 220) { return getModuleInstanceState(node.body); } else { @@ -9937,6 +10162,8 @@ var ts; file.symbolCount = symbolCount; file.classifiableNames = classifiableNames; } + file = undefined; + options = undefined; parent = undefined; container = undefined; blockScopeContainer = undefined; @@ -9965,13 +10192,17 @@ var ts; if (symbolFlags & 6240 && !symbol.members) { symbol.members = {}; } - if (symbolFlags & 107455 && !symbol.valueDeclaration) { - symbol.valueDeclaration = node; + if (symbolFlags & 107455) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 220)) { + symbol.valueDeclaration = node; + } } } function getDeclarationName(node) { if (node.name) { - if (node.kind === 218 && node.name.kind === 9) { + if (node.kind === 220 && node.name.kind === 9) { return "\"" + node.name.text + "\""; } if (node.name.kind === 136) { @@ -9995,14 +10226,24 @@ var ts; return "__new"; case 149: return "__index"; - case 228: + case 230: return "__export"; - case 227: + case 229: return node.isExportEquals ? "export=" : "default"; - case 181: - return "export="; - case 213: - case 214: + case 183: + switch (ts.getSpecialPropertyAssignmentKind(node)) { + case 2: + return "export="; + case 1: + case 4: + return node.left.name.text; + case 3: + return node.left.expression.name.text; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 215: + case 216: return node.flags & 512 ? "default" : undefined; } } @@ -10050,7 +10291,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedNodeFlags(node) & 2; if (symbolFlags & 8388608) { - if (node.kind === 230 || (node.kind === 221 && hasExportModifier)) { + if (node.kind === 232 || (node.kind === 223 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -10097,10 +10338,10 @@ var ts; var kind = node.kind; var flags = node.flags; flags &= ~1572864; - if (kind === 215) { + if (kind === 217) { seenThisKeyword = false; } - var saveState = kind === 248 || kind === 219 || ts.isFunctionLikeKind(kind); + var saveState = kind === 250 || kind === 221 || ts.isFunctionLikeKind(kind); if (saveState) { savedReachabilityState = currentReachabilityState; savedLabelStack = labelStack; @@ -10118,7 +10359,7 @@ var ts; flags |= 1048576; } } - if (kind === 215) { + if (kind === 217) { flags = seenThisKeyword ? flags | 262144 : flags & ~262144; } node.flags = flags; @@ -10139,40 +10380,40 @@ var ts; return; } switch (node.kind) { - case 198: + case 200: bindWhileStatement(node); break; - case 197: + case 199: bindDoStatement(node); break; - case 199: + case 201: bindForStatement(node); break; - case 200: - case 201: + case 202: + case 203: bindForInOrForOfStatement(node); break; - case 196: + case 198: bindIfStatement(node); break; - case 204: - case 208: + case 206: + case 210: bindReturnOrThrow(node); break; - case 203: - case 202: + case 205: + case 204: bindBreakOrContinueStatement(node); break; - case 209: + case 211: bindTryStatement(node); break; - case 206: + case 208: bindSwitchStatement(node); break; - case 220: + case 222: bindCaseBlock(node); break; - case 207: + case 209: bindLabeledStatement(node); break; default: @@ -10234,14 +10475,14 @@ var ts; } function bindReturnOrThrow(n) { bind(n.expression); - if (n.kind === 204) { + if (n.kind === 206) { hasExplicitReturn = true; } currentReachabilityState = 4; } function bindBreakOrContinueStatement(n) { bind(n.label); - var isValidJump = jumpToLabel(n.label, n.kind === 203 ? currentReachabilityState : 4); + var isValidJump = jumpToLabel(n.label, n.kind === 205 ? currentReachabilityState : 4); if (isValidJump) { currentReachabilityState = 4; } @@ -10262,7 +10503,7 @@ var ts; var postSwitchLabel = pushImplicitLabel(); bind(n.expression); bind(n.caseBlock); - var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242; }); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 244; }); var postSwitchState = hasDefault && currentReachabilityState !== 2 ? 4 : preSwitchState; popImplicitLabel(postSwitchLabel, postSwitchState); } @@ -10287,37 +10528,37 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 186: - case 214: - case 215: + case 188: + case 216: case 217: + case 219: case 155: - case 165: + case 167: return 1; case 147: case 148: case 149: case 143: case 142: - case 213: + case 215: case 144: case 145: case 146: case 152: case 153: - case 173: - case 174: - case 218: - case 248: - case 216: - return 5; - case 244: - case 199: - case 200: - case 201: + case 175: + case 176: case 220: + case 250: + case 218: + return 5; + case 246: + case 201: + case 202: + case 203: + case 222: return 2; - case 192: + case 194: return ts.isFunctionLike(node.parent) ? 0 : 2; } return 0; @@ -10333,18 +10574,18 @@ var ts; } function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { switch (container.kind) { - case 218: + case 220: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 248: + case 250: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 186: - case 214: + case 188: + case 216: return declareClassMember(node, symbolFlags, symbolExcludes); - case 217: + case 219: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case 155: - case 165: - case 215: + case 167: + case 217: return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); case 152: case 153: @@ -10356,10 +10597,10 @@ var ts; case 144: case 145: case 146: - case 213: - case 173: - case 174: - case 216: + case 215: + case 175: + case 176: + case 218: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } @@ -10374,11 +10615,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 248 ? node : node.body; - if (body.kind === 248 || body.kind === 219) { + var body = node.kind === 250 ? node : node.body; + if (body.kind === 250 || body.kind === 221) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 228 || stat.kind === 227) { + if (stat.kind === 230 || stat.kind === 229) { return true; } } @@ -10437,7 +10678,7 @@ var ts; continue; } var identifier = prop.name; - var currentKind = prop.kind === 245 || prop.kind === 246 || prop.kind === 143 + var currentKind = prop.kind === 247 || prop.kind === 248 || prop.kind === 143 ? 1 : 2; var existingKind = seen[identifier.text]; @@ -10459,10 +10700,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 218: + case 220: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 248: + case 250: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -10584,17 +10825,17 @@ var ts; } function updateStrictMode(node) { switch (node.kind) { - case 248: - case 219: + case 250: + case 221: updateStrictModeStatementList(node.statements); return; - case 192: + case 194: if (ts.isFunctionLike(node.parent)) { updateStrictModeStatementList(node.statements); } return; - case 214: - case 186: + case 216: + case 188: inStrictMode = true; return; } @@ -10619,45 +10860,60 @@ var ts; switch (node.kind) { case 69: return checkStrictModeIdentifier(node); - case 181: + case 183: if (ts.isInJavaScriptFile(node)) { - if (ts.isExportsPropertyAssignment(node)) { - bindExportsPropertyAssignment(node); - } - else if (ts.isModuleExportsAssignment(node)) { - bindModuleExportsAssignment(node); + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1: + bindExportsPropertyAssignment(node); + break; + case 2: + bindModuleExportsAssignment(node); + break; + case 3: + bindPrototypePropertyAssignment(node); + break; + case 4: + bindThisPropertyAssignment(node); + break; + case 0: + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); } } return checkStrictModeBinaryExpression(node); - case 244: + case 246: return checkStrictModeCatchClause(node); - case 175: + case 177: return checkStrictModeDeleteExpression(node); case 8: return checkStrictModeNumericLiteral(node); - case 180: + case 182: return checkStrictModePostfixUnaryExpression(node); - case 179: + case 181: return checkStrictModePrefixUnaryExpression(node); - case 205: + case 207: return checkStrictModeWithStatement(node); - case 97: + case 161: seenThisKeyword = true; return; + case 150: + return checkTypePredicate(node); case 137: return declareSymbolAndAddToSymbolTable(node, 262144, 530912); case 138: return bindParameter(node); - case 211: - case 163: + case 213: + case 165: return bindVariableDeclarationOrBindingElement(node); case 141: case 140: return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455); - case 245: - case 246: - return bindPropertyOrMethodOrAccessor(node, 4, 107455); case 247: + case 248: + return bindPropertyOrMethodOrAccessor(node, 4, 107455); + case 249: return bindPropertyOrMethodOrAccessor(node, 8, 107455); case 147: case 148: @@ -10666,7 +10922,7 @@ var ts; case 143: case 142: return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263); - case 213: + case 215: checkStrictModeFunctionName(node); return declareSymbolAndAddToSymbolTable(node, 16, 106927); case 144: @@ -10680,44 +10936,54 @@ var ts; return bindFunctionOrConstructorType(node); case 155: return bindAnonymousDeclaration(node, 2048, "__type"); - case 165: + case 167: return bindObjectLiteralExpression(node); - case 173: - case 174: + case 175: + case 176: checkStrictModeFunctionName(node); var bindingName = node.name ? node.name.text : "__function"; return bindAnonymousDeclaration(node, 16, bindingName); - case 168: + case 170: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; - case 186: - case 214: - return bindClassLikeDeclaration(node); - case 215: - return bindBlockScopedDeclaration(node, 64, 792960); + case 188: case 216: - return bindBlockScopedDeclaration(node, 524288, 793056); + return bindClassLikeDeclaration(node); case 217: - return bindEnumDeclaration(node); + return bindBlockScopedDeclaration(node, 64, 792960); case 218: + return bindBlockScopedDeclaration(node, 524288, 793056); + case 219: + return bindEnumDeclaration(node); + case 220: return bindModuleDeclaration(node); - case 221: - case 224: - case 226: - case 230: - return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); case 223: - return bindImportClause(node); + case 226: case 228: + case 232: + return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + case 225: + return bindImportClause(node); + case 230: return bindExportDeclaration(node); - case 227: + case 229: return bindExportAssignment(node); - case 248: + case 250: return bindSourceFileIfExternalModule(); } } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 69) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 161) { + seenThisKeyword = true; + } + bind(type); + } function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (ts.isExternalModule(file)) { @@ -10728,7 +10994,7 @@ var ts; bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { - var boundExpression = node.kind === 227 ? node.expression : node.right; + var boundExpression = node.kind === 229 ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } @@ -10766,13 +11032,30 @@ var ts; setCommonJsModuleIndicator(node); bindExportAssignment(node); } + function bindThisPropertyAssignment(node) { + if (container.kind === 175 || container.kind === 215) { + container.symbol.members = container.symbol.members || {}; + declareSymbol(container.symbol.members, container.symbol, node, 4, 107455); + } + } + function bindPrototypePropertyAssignment(node) { + var classId = node.left.expression.expression; + var funcSymbol = container.locals[classId.text]; + if (!funcSymbol || !(funcSymbol.flags & 16)) { + return; + } + if (!funcSymbol.members) { + funcSymbol.members = {}; + } + declareSymbol(funcSymbol.members, funcSymbol, node.left, 4, 107455); + } function bindCallExpression(node) { if (!file.commonJsModuleIndicator && ts.isRequireCall(node)) { setCommonJsModuleIndicator(node); } } function bindClassLikeDeclaration(node) { - if (node.kind === 214) { + if (node.kind === 216) { bindBlockScopedDeclaration(node, 32, 899519); } else { @@ -10824,9 +11107,7 @@ var ts; else { declareSymbolAndAddToSymbolTable(node, 1, 107455); } - if (node.flags & 56 && - node.parent.kind === 144 && - ts.isClassLike(node.parent.parent)) { + if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); } @@ -10891,15 +11172,15 @@ var ts; function checkUnreachable(node) { switch (currentReachabilityState) { case 4: - var reportError = (ts.isStatement(node) && node.kind !== 194) || - node.kind === 214 || - (node.kind === 218 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 217 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + var reportError = (ts.isStatement(node) && node.kind !== 196) || + node.kind === 216 || + (node.kind === 220 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 219 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentReachabilityState = 8; var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && - (node.kind !== 193 || + (node.kind !== 195 || ts.getCombinedNodeFlags(node.declarationList) & 24576 || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -10933,15 +11214,18 @@ var ts; var nextNodeId = 1; var nextMergeId = 1; function getNodeId(node) { - if (!node.id) - node.id = nextNodeId++; + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } return node.id; } ts.getNodeId = getNodeId; ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { - symbol.id = nextSymbolId++; + symbol.id = nextSymbolId; + nextSymbolId++; } return symbol.id; } @@ -10958,8 +11242,10 @@ var ts; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0; var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 ? 5 : 0; + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === 4; var emitResolver = createResolver(); var undefinedSymbol = createSymbol(4 | 67108864, "undefined"); + undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 | 67108864, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -10971,6 +11257,7 @@ var ts; getDiagnostics: getDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, getTypeOfSymbolAtLocation: getNarrowedTypeOfSymbol, + getSymbolsOfParameterPropertyDeclaration: getSymbolsOfParameterPropertyDeclaration, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: getPropertyOfType, @@ -10987,7 +11274,7 @@ var ts; symbolToString: symbolToString, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: getApparentTypeOfContextualType, + getContextualType: getContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: getResolvedSignature, getConstantValue: getConstantValue, @@ -11012,15 +11299,15 @@ var ts; var undefinedType = createIntrinsicType(32 | 2097152, "undefined"); var nullType = createIntrinsicType(64 | 2097152, "null"); var unknownType = createIntrinsicType(1, "unknown"); - var circularType = createIntrinsicType(1, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyUnionType = emptyObjectType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); anyFunctionType.flags |= 8388608; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); var globals = {}; var globalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; @@ -11033,8 +11320,6 @@ var ts; var globalRegExpType; var globalTemplateStringsArrayType; var globalESSymbolType; - var jsxElementType; - var jsxIntrinsicElementsType; var globalIterableType; var globalIteratorType; var globalIterableIteratorType; @@ -11051,6 +11336,7 @@ var ts; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; var jsxElementClassType; + var deferredNodes; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; @@ -11085,19 +11371,31 @@ var ts; "symbol": { type: esSymbolType, flags: 16777216 + }, + "undefined": { + type: undefinedType, + flags: 2097152 } }; + var jsxElementType; + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", ElementClass: "ElementClass", ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - Element: "Element" + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" }; var subtypeRelation = {}; var assignableRelation = {}; var identityRelation = {}; var _displayBuilder; + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -11151,8 +11449,10 @@ var ts; return result; } function recordMergedSymbol(target, source) { - if (!source.mergeId) - source.mergeId = nextMergeId++; + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { @@ -11176,8 +11476,11 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (!target.valueDeclaration && source.valueDeclaration) + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 220 && source.valueDeclaration.kind !== 220))) { target.valueDeclaration = source.valueDeclaration; + } ts.forEach(source.declarations, function (node) { target.declarations.push(node); }); @@ -11229,6 +11532,21 @@ 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]; + } + } + } + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } function getSymbolLinks(symbol) { if (symbol.flags & 67108864) return symbol; @@ -11240,10 +11558,16 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function getSourceFile(node) { - return ts.getAncestor(node, 248); + return ts.getAncestor(node, 250); } function isGlobalSourceFile(node) { - return node.kind === 248 && !ts.isExternalOrCommonJsModule(node); + return node.kind === 250 && !ts.isExternalOrCommonJsModule(node); + } + function isPrimitiveApparentType(type) { + return type === globalStringType || + type === globalNumberType || + type === globalBooleanType || + type === globalESSymbolType; } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -11260,6 +11584,16 @@ var ts; } } } + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructoDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructoDeclaration.locals, parameterName, 107455); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); @@ -11271,18 +11605,18 @@ var ts; return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { - return declaration.kind !== 211 || + return declaration.kind !== 213 || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } return isUsedInFunctionOrNonStaticProperty(declaration, usage); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); - if (declaration.parent.parent.kind === 193 || - declaration.parent.parent.kind === 199) { + if (declaration.parent.parent.kind === 195 || + declaration.parent.parent.kind === 201) { return isSameScopeDescendentOf(usage, declaration, container); } - else if (declaration.parent.parent.kind === 201 || - declaration.parent.parent.kind === 200) { + else if (declaration.parent.parent.kind === 203 || + declaration.parent.parent.kind === 202) { var expression = declaration.parent.parent.expression; return isSameScopeDescendentOf(usage, expression, container); } @@ -11318,23 +11652,38 @@ var ts; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { - if (!(meaning & 793056) || - !(result.flags & (793056 & ~262144)) || - !ts.isFunctionLike(location) || - lastLocation === location.body) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + if (meaning & result.flags & 793056) { + useResult = result.flags & 262144 + ? lastLocation === location.type || + lastLocation.kind === 138 || + lastLocation.kind === 137 + : false; + } + if (meaning & 107455 && result.flags & 1) { + useResult = + lastLocation.kind === 138 || + (lastLocation === location.type && + result.valueDeclaration.kind === 138); + } + } + if (useResult) { break loop; } - result = undefined; + else { + result = undefined; + } } } switch (location.kind) { - case 248: + case 250: if (!ts.isExternalOrCommonJsModule(location)) break; - case 218: + case 220: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 248 || - (location.kind === 218 && location.name.kind === 9)) { + if (location.kind === 250 || + (location.kind === 220 && location.name.kind === 9)) { if (result = moduleExports["default"]) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { @@ -11344,7 +11693,7 @@ var ts; } if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 && - ts.getDeclarationOfKind(moduleExports[name], 230)) { + ts.getDeclarationOfKind(moduleExports[name], 232)) { break; } } @@ -11352,7 +11701,7 @@ var ts; break loop; } break; - case 217: + case 219: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } @@ -11368,9 +11717,9 @@ var ts; } } break; - case 214: - case 186: - case 215: + case 216: + case 188: + case 217: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { if (lastLocation && lastLocation.flags & 64) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); @@ -11378,7 +11727,7 @@ var ts; } break loop; } - if (location.kind === 186 && meaning & 32) { + if (location.kind === 188 && meaning & 32) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -11388,7 +11737,7 @@ var ts; break; case 136: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 215) { + if (ts.isClassLike(grandparent) || grandparent.kind === 217) { if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; @@ -11400,14 +11749,14 @@ var ts; case 144: case 145: case 146: - case 213: - case 174: + case 215: + case 176: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 173: + case 175: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -11460,7 +11809,7 @@ var ts; ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 211), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 213), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -11477,10 +11826,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 221) { + if (node.kind === 223) { return node; } - while (node && node.kind !== 222) { + while (node && node.kind !== 224) { node = node.parent; } return node; @@ -11490,7 +11839,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 232) { + if (node.moduleReference.kind === 234) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -11499,9 +11848,12 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); - if (!exportDefaultSymbol) { + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveSymbol(moduleSymbol.exports["export="]) || resolveSymbol(moduleSymbol); + } return exportDefaultSymbol; } } @@ -11509,14 +11861,6 @@ var ts; var moduleSpecifier = node.parent.parent.moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } - function getMemberOfModuleVariable(moduleSymbol, name) { - if (moduleSymbol.flags & 3) { - var typeAnnotation = moduleSymbol.valueDeclaration.type; - if (typeAnnotation) { - return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); - } - } - } function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { if (valueSymbol.flags & (793056 | 1536)) { return valueSymbol; @@ -11579,17 +11923,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 221: - return getTargetOfImportEqualsDeclaration(node); case 223: + return getTargetOfImportEqualsDeclaration(node); + case 225: return getTargetOfImportClause(node); - case 224: - return getTargetOfNamespaceImport(node); case 226: + return getTargetOfNamespaceImport(node); + case 228: return getTargetOfImportSpecifier(node); - case 230: + case 232: return getTargetOfExportSpecifier(node); - case 227: + case 229: return getTargetOfExportAssignment(node); } } @@ -11631,10 +11975,10 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 227) { + if (node.kind === 229) { checkExpressionCached(node.expression); } - else if (node.kind === 230) { + else if (node.kind === 232) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -11644,7 +11988,7 @@ var ts; } function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 221); + importDeclaration = ts.getAncestor(entityName, 223); ts.Debug.assert(importDeclaration !== undefined); } if (entityName.kind === 69 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { @@ -11654,7 +11998,7 @@ var ts; return resolveEntityName(entityName, 1536); } else { - ts.Debug.assert(entityName.parent.kind === 221); + ts.Debug.assert(entityName.parent.kind === 223); return resolveEntityName(entityName, 107455 | 793056 | 1536); } } @@ -11673,7 +12017,7 @@ var ts; return undefined; } } - else if (name.kind === 135 || name.kind === 166) { + else if (name.kind === 135 || name.kind === 168) { var left = name.kind === 135 ? name.left : name.expression; var right = name.kind === 135 ? name.right : name.name; var namespace = resolveEntityName(left, 1536, ignoreErrors); @@ -11699,14 +12043,10 @@ var ts; return; } var moduleReferenceLiteral = moduleReferenceExpression; - var searchPath = ts.getDirectoryPath(getSourceFile(location).fileName); var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); if (moduleName === undefined) { return; } - if (moduleName.indexOf("!") >= 0) { - moduleName = moduleName.substr(0, moduleName.indexOf("!")); - } var isRelative = ts.isExternalModuleNameRelative(moduleName); if (!isRelative) { var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); @@ -11749,35 +12089,58 @@ var ts; var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } - function extendExportSymbols(target, source) { + function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; + if (lookupTable && exportNode) { + lookupTable[id] = { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }; + } + } + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + if (!lookupTable[id].exportsWithDuplicate) { + lookupTable[id].exportsWithDuplicate = [exportNode]; + } + else { + lookupTable[id].exportsWithDuplicate.push(exportNode); + } } } } function getExportsForModule(moduleSymbol) { - var result; var visitedSymbols = []; - visit(moduleSymbol); - return result || moduleSymbol.exports; + return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { - if (symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol)) { - visitedSymbols.push(symbol); - if (symbol !== moduleSymbol) { - if (!result) { - result = cloneSymbolTable(moduleSymbol.exports); - } - extendExportSymbols(result, symbol.exports); - } - var exportStars = symbol.exports["__export"]; - if (exportStars) { - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - visit(resolveExternalModuleName(node, node.moduleSpecifier)); - } - } + if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { + return; } + visitedSymbols.push(symbol); + var symbols = cloneSymbolTable(symbol.exports); + var exportStars = symbol.exports["__export"]; + if (exportStars) { + var nestedSymbols = {}; + var lookupTable = {}; + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node); + } + for (var id in lookupTable) { + var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + continue; + } + for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { + var node = exportsWithDuplicate_1[_b]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable[id].specifierText, id)); + } + } + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; } } function getMergedSymbol(symbol) { @@ -11818,7 +12181,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount++; + result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -11876,17 +12240,17 @@ var ts; } } switch (location_1.kind) { - case 248: + case 250: if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 218: + case 220: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 214: - case 215: + case 216: + case 217: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -11919,7 +12283,7 @@ var ts; return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230)) { + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 232)) { if (!useOnlyExternalAliasing || ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); @@ -11948,7 +12312,7 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 232)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -12003,8 +12367,8 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 218 && declaration.name.kind === 9) || - (declaration.kind === 248 && ts.isExternalOrCommonJsModule(declaration)); + return (declaration.kind === 220 && declaration.name.kind === 9) || + (declaration.kind === 250 && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -12039,8 +12403,8 @@ var ts; if (entityName.parent.kind === 154) { meaning = 107455 | 1048576; } - else if (entityName.kind === 135 || entityName.kind === 166 || - entityName.parent.kind === 221) { + else if (entityName.kind === 135 || entityName.kind === 168 || + entityName.parent.kind === 223) { meaning = 1536; } else { @@ -12070,9 +12434,9 @@ var ts; ts.releaseStringWriter(writer); return result; } - function signatureToString(signature, enclosingDeclaration, flags) { + function signatureToString(signature, enclosingDeclaration, flags, kind) { var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); var result = writer.string(); ts.releaseStringWriter(writer); return result; @@ -12094,7 +12458,7 @@ var ts; while (node.kind === 160) { node = node.parent; } - if (node.kind === 216) { + if (node.kind === 218) { return getSymbolOfNode(node); } } @@ -12108,10 +12472,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 186: + case 188: return "(Anonymous class)"; - case 173: - case 174: + case 175: + case 176: return "(Anonymous function)"; } } @@ -12176,9 +12540,15 @@ var ts; return writeType(type, globalFlags); function writeType(type, flags) { if (type.flags & 16777343) { - writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) - ? "any" - : type.intrinsicName); + if (type.flags & 134217728) { + buildTypePredicateDisplay(writer, type.predicate); + buildTypeDisplay(type.predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } + else { + writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) + ? "any" + : type.intrinsicName); + } } else if (type.flags & 33554432) { if (inObjectTypeLiteral) { @@ -12230,11 +12600,13 @@ var ts; } if (pos < end) { writePunctuation(writer, 25); - writeType(typeArguments[pos++], 0); + writeType(typeArguments[pos], 0); + pos++; while (pos < end) { writePunctuation(writer, 24); writeSpace(writer); - writeType(typeArguments[pos++], 0); + writeType(typeArguments[pos], 0); + pos++; } writePunctuation(writer, 27); } @@ -12317,7 +12689,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 248 || declaration.parent.kind === 219; + return declaration.parent.kind === 250 || declaration.parent.kind === 221; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 2) || @@ -12350,7 +12722,7 @@ var ts; if (flags & 64) { writePunctuation(writer, 17); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (flags & 64) { writePunctuation(writer, 18); } @@ -12362,7 +12734,7 @@ var ts; } writeKeyword(writer, 92); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (flags & 64) { writePunctuation(writer, 18); } @@ -12376,15 +12748,13 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - writeKeyword(writer, 92); - writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } @@ -12425,7 +12795,7 @@ var ts; if (p.flags & 536870912) { writePunctuation(writer, 53); } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } @@ -12513,6 +12883,17 @@ var ts; } writePunctuation(writer, 18); } + function buildTypePredicateDisplay(writer, predicate) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 97); + } + writeSpace(writer); + writeKeyword(writer, 124); + writeSpace(writer); + } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8) { writeSpace(writer); @@ -12522,20 +12903,14 @@ var ts; writePunctuation(writer, 54); } writeSpace(writer); - var returnType; - if (signature.typePredicate) { - writer.writeParameter(signature.typePredicate.parameterName); - writeSpace(writer); - writeKeyword(writer, 124); - writeSpace(writer); - returnType = signature.typePredicate.type; - } - else { - returnType = getReturnTypeOfSignature(signature); - } + var returnType = getReturnTypeOfSignature(signature); buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1) { + writeKeyword(writer, 92); + writeSpace(writer); + } if (signature.target && (flags & 32)) { buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); } @@ -12558,73 +12933,33 @@ var ts; }); } function isDeclarationVisible(node) { - function getContainingExternalModule(node) { - for (; node; node = node.parent) { - if (node.kind === 218) { - if (node.name.kind === 9) { - return node; - } - } - else if (node.kind === 248) { - return ts.isExternalOrCommonJsModule(node) ? node : undefined; - } - } - ts.Debug.fail("getContainingModule cant reach here"); - } - function isUsedInExportAssignment(node) { - var externalModule = getContainingExternalModule(node); - var exportAssignmentSymbol; - var resolvedExportSymbol; - if (externalModule) { - var externalModuleSymbol = getSymbolOfNode(externalModule); - exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); - var symbolOfNode = getSymbolOfNode(node); - if (isSymbolUsedInExportAssignment(symbolOfNode)) { - return true; - } - if (symbolOfNode.flags & 8388608) { - return isSymbolUsedInExportAssignment(resolveAlias(symbolOfNode)); - } - } - function isSymbolUsedInExportAssignment(symbol) { - if (exportAssignmentSymbol === symbol) { - return true; - } - if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 8388608)) { - resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol); - if (resolvedExportSymbol === symbol) { - return true; - } - return ts.forEach(resolvedExportSymbol.declarations, function (current) { - while (current) { - if (current === node) { - return true; - } - current = current.parent; - } - }); - } + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); } + return links.isVisible; } + return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 163: + case 165: return isDeclarationVisible(node.parent.parent); - case 211: + case 213: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { return false; } - case 218: - case 214: - case 215: + case 220: case 216: - case 213: case 217: - case 221: + case 218: + case 215: + case 219: + case 223: var parent_4 = getDeclarationContainer(node); if (!(ts.getCombinedNodeFlags(node) & 2) && - !(node.kind !== 221 && parent_4.kind !== 248 && ts.isInAmbientContext(parent_4))) { + !(node.kind !== 223 && parent_4.kind !== 250 && ts.isInAmbientContext(parent_4))) { return isGlobalSourceFile(parent_4); } return isDeclarationVisible(parent_4); @@ -12642,7 +12977,7 @@ var ts; case 147: case 149: case 138: - case 219: + case 221: case 152: case 153: case 155: @@ -12653,33 +12988,26 @@ var ts; case 159: case 160: return isDeclarationVisible(node.parent); - case 223: - case 224: + case 225: case 226: + case 228: return false; case 137: - case 248: + case 250: return true; - case 227: + case 229: return false; default: ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); } } - if (node) { - var links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 227) { + if (node.parent && node.parent.kind === 229) { exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 230) { + else if (node.parent.kind === 232) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -12754,7 +13082,7 @@ var ts; } function getDeclarationContainer(node) { node = ts.getRootDeclaration(node); - return node.kind === 211 ? node.parent.parent.parent : node.parent; + return node.kind === 213 ? node.parent.parent.parent : node.parent; } function getTypeOfPrototypeProperty(prototype) { var classType = getDeclaredTypeOfSymbol(prototype.parent); @@ -12801,7 +13129,7 @@ var ts; return parentType; } var type; - if (pattern.kind === 161) { + if (pattern.kind === 163) { var name_10 = declaration.propertyName || declaration.name; if (isComputedNonLiteralName(name_10)) { return anyType; @@ -12839,10 +13167,10 @@ var ts; return type; } function getTypeForVariableLikeDeclaration(declaration) { - if (declaration.parent.parent.kind === 200) { + if (declaration.parent.parent.kind === 202) { return anyType; } - if (declaration.parent.parent.kind === 201) { + if (declaration.parent.parent.kind === 203) { return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -12867,7 +13195,7 @@ var ts; if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } - if (declaration.kind === 246) { + if (declaration.kind === 248) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { @@ -12914,7 +13242,7 @@ var ts; 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 === 187 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return e.kind === 189 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { var result = createNewTupleType(elementTypes); result.pattern = pattern; @@ -12923,7 +13251,7 @@ var ts; return createTupleType(elementTypes); } function getTypeFromBindingPattern(pattern, includePatternInType) { - return pattern.kind === 161 + return pattern.kind === 163 ? getTypeFromObjectBindingPattern(pattern, includePatternInType) : getTypeFromArrayBindingPattern(pattern, includePatternInType); } @@ -12933,7 +13261,13 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - return declaration.kind !== 245 ? getWidenedType(type) : type; + if (declaration.kind === 247) { + return type; + } + if (type.flags & 134217728 && (declaration.kind === 141 || declaration.kind === 140)) { + return type; + } + return getWidenedType(type); } type = declaration.dotDotDotToken ? anyArrayType : anyType; if (reportErrors && compilerOptions.noImplicitAny) { @@ -12951,17 +13285,19 @@ var ts; return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 244) { + if (declaration.parent.kind === 246) { return links.type = anyType; } - if (declaration.kind === 227) { + if (declaration.kind === 229) { return links.type = checkExpression(declaration.expression); } - if (declaration.kind === 181) { + if (declaration.kind === 183) { return links.type = checkExpression(declaration.right); } - if (declaration.kind === 166) { - return checkExpressionCached(declaration.parent.right); + if (declaration.kind === 168) { + if (declaration.parent.kind === 183) { + return links.type = checkExpressionCached(declaration.parent.right); + } } if (!pushTypeResolution(symbol, 0)) { return unknownType; @@ -13117,9 +13453,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 214 || node.kind === 186 || - node.kind === 213 || node.kind === 173 || - node.kind === 143 || node.kind === 174) { + if (node.kind === 216 || node.kind === 188 || + node.kind === 215 || node.kind === 175 || + node.kind === 143 || node.kind === 176) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -13128,15 +13464,15 @@ var ts; } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 215); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 217); return appendOuterTypeParameters(undefined, declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 215 || node.kind === 214 || - node.kind === 186 || node.kind === 216) { + if (node.kind === 217 || node.kind === 216 || + node.kind === 188 || node.kind === 218) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -13191,9 +13527,6 @@ var ts; } return type.resolvedBaseConstructorType; } - function hasClassBaseType(type) { - return !!ts.forEach(getBaseTypes(type), function (t) { return !!(t.symbol.flags & 32); }); - } function getBaseTypes(type) { var isClass = type.symbol.flags & 32; var isInterface = type.symbol.flags & 64; @@ -13262,7 +13595,7 @@ var ts; type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 217 && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -13291,7 +13624,7 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215) { + if (declaration.kind === 217) { if (declaration.flags & 262144) { return false; } @@ -13340,7 +13673,7 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 216); + var declaration = ts.getDeclarationOfKind(symbol, 218); var type = getTypeFromTypeNode(declaration.type); if (popTypeResolution()) { links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -13423,7 +13756,7 @@ var ts; case 120: case 131: case 103: - case 9: + case 162: return true; case 156: return isIndependentType(node.elementType); @@ -13488,14 +13821,6 @@ var ts; } } } - function addInheritedSignatures(signatures, baseSignatures) { - if (baseSignatures) { - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var signature = baseSignatures_1[_i]; - signatures.push(signature); - } - } - } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; @@ -13556,33 +13881,32 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, parameters, resolvedReturnType, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - if (!hasClassBaseType(classType)) { - return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, 0, false, false)]; + } var baseTypeNode = getBaseTypeNodeOfClass(classType); var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { - var baseSig = baseSignatures_2[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -13612,7 +13936,7 @@ var ts; function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreReturnTypes, compareTypesIdentical)) { return s; } } @@ -13701,35 +14025,28 @@ var ts; } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; - var members; - var callSignatures; - var constructSignatures; - var stringIndexType; - var numberIndexType; if (type.target) { - members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); - callSignatures = instantiateList(getSignaturesOfType(type.target, 0), type.mapper, instantiateSignature); - constructSignatures = instantiateList(getSignaturesOfType(type.target, 1), type.mapper, instantiateSignature); - stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0), type.mapper); - numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1), type.mapper); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); + var callSignatures = instantiateList(getSignaturesOfType(type.target, 0), type.mapper, instantiateSignature); + var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1), type.mapper, instantiateSignature); + var stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0), type.mapper); + var numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1), type.mapper); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } else if (symbol.flags & 2048) { - members = symbol.members; - callSignatures = getSignaturesOfSymbol(members["__call"]); - constructSignatures = getSignaturesOfSymbol(members["__new"]); - stringIndexType = getIndexTypeOfSymbol(symbol, 0); - numberIndexType = getIndexTypeOfSymbol(symbol, 1); + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members["__call"]); + var constructSignatures = getSignaturesOfSymbol(members["__new"]); + var stringIndexType = getIndexTypeOfSymbol(symbol, 0); + var numberIndexType = getIndexTypeOfSymbol(symbol, 1); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } else { - members = emptySymbols; - callSignatures = emptyArray; - constructSignatures = emptyArray; + var members = emptySymbols; + var constructSignatures = emptyArray; if (symbol.flags & 1952) { members = getExportsOfSymbol(symbol); } - if (symbol.flags & (16 | 8192)) { - callSignatures = getSignaturesOfSymbol(symbol); - } if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); @@ -13742,10 +14059,12 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } - stringIndexType = undefined; - numberIndexType = (symbol.flags & 384) ? stringType : undefined; + var numberIndexType = (symbol.flags & 384) ? stringType : undefined; + setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexType); + if (symbol.flags & (16 | 8192)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -13835,12 +14154,14 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; + var commonFlags = (containingType.flags & 32768) ? 536870912 : 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 | 32))) { + commonFlags &= prop.flags; if (!props) { props = [prop]; } @@ -13868,7 +14189,10 @@ var ts; } propTypes.push(getTypeOfSymbol(prop)); } - var result = createSymbol(4 | 67108864 | 268435456, name); + var result = createSymbol(4 | + 67108864 | + 268435456 | + commonFlags, name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & 16384 ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -13918,22 +14242,6 @@ var ts; function getSignaturesOfType(type, kind) { return getSignaturesOfStructuredType(getApparentType(type), kind); } - function typeHasConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & (80896 | 16384)) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.constructSignatures.length > 0; - } - return false; - } - function typeHasCallOrConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & 130048) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; - } - return false; - } function getIndexTypeOfStructuredType(type, kind) { if (type.flags & 130048) { var resolved = resolveStructuredTypeMembers(type); @@ -13975,6 +14283,23 @@ var ts; } return false; } + function createTypePredicateFromTypePredicateNode(node) { + if (node.parameterName.kind === 69) { + var parameterName = node.parameterName; + return { + kind: 1, + parameterName: parameterName ? parameterName.text : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0, + type: getTypeFromTypeNode(node.type) + }; + } + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { @@ -13988,8 +14313,13 @@ var ts; var minArgumentCount = -1; for (var i = 0, n = declaration.parameters.length; i < n; i++) { var param = declaration.parameters[i]; - parameters.push(param.symbol); - if (param.type && param.type.kind === 9) { + var paramSymbol = param.symbol; + if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.name, 107455, undefined, undefined); + paramSymbol = resolvedSymbol; + } + parameters.push(paramSymbol); + if (param.type && param.type.kind === 162) { hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken) { @@ -14005,20 +14335,11 @@ var ts; minArgumentCount = declaration.parameters.length; } var returnType; - var typePredicate; if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); - if (declaration.type.kind === 150) { - var typePredicateNode = declaration.type; - typePredicate = { - parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, - parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, - type: getTypeFromTypeNode(typePredicateNode.type) - }; - } } else { if (declaration.kind === 145 && !ts.hasDynamicName(declaration)) { @@ -14029,7 +14350,7 @@ var ts; returnType = anyType; } } - links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -14042,7 +14363,7 @@ var ts; switch (node.kind) { case 152: case 153: - case 213: + case 215: case 143: case 142: case 144: @@ -14051,8 +14372,8 @@ var ts; case 149: case 145: case 146: - case 173: - case 174: + case 175: + case 176: if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -14168,17 +14489,38 @@ var ts; ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType : undefined; } - function getConstraintOfTypeParameter(type) { - if (!type.constraint) { - if (type.target) { - var targetConstraint = getConstraintOfTypeParameter(type.target); - type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 137).constraint; + } + function hasConstraintReferenceTo(type, target) { + var checked; + while (type && type.flags & 512 && !ts.contains(checked, type)) { + if (type === target) { + return true; + } + (checked || (checked = [])).push(type); + var constraintDeclaration = getConstraintDeclaration(type); + type = constraintDeclaration && getTypeFromTypeNode(constraintDeclaration); + } + return false; + } + function getConstraintOfTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 137).constraint); + var constraintDeclaration = getConstraintDeclaration(typeParameter); + var constraint = getTypeFromTypeNode(constraintDeclaration); + if (hasConstraintReferenceTo(constraint, typeParameter)) { + error(constraintDeclaration, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + constraint = unknownType; + } + typeParameter.constraint = constraint; } } - return type.constraint === noConstraintType ? undefined : type.constraint; + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 137).parent); @@ -14222,40 +14564,6 @@ var ts; } return type; } - function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode, typeParameterSymbol) { - var links = getNodeLinks(typeReferenceNode); - if (links.isIllegalTypeReferenceInConstraint !== undefined) { - return links.isIllegalTypeReferenceInConstraint; - } - var currentNode = typeReferenceNode; - while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { - currentNode = currentNode.parent; - } - links.isIllegalTypeReferenceInConstraint = currentNode.kind === 137; - return links.isIllegalTypeReferenceInConstraint; - } - function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { - var typeParameterSymbol; - function check(n) { - if (n.kind === 151 && n.typeName.kind === 69) { - var links = getNodeLinks(n); - if (links.isIllegalTypeReferenceInConstraint === undefined) { - var symbol = resolveName(typeParameter, n.typeName.text, 793056, undefined, undefined); - if (symbol && (symbol.flags & 262144)) { - links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent === typeParameter.parent; }); - } - } - if (links.isIllegalTypeReferenceInConstraint) { - error(typeParameter, ts.Diagnostics.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); - } - } - ts.forEachChild(n, check); - } - if (typeParameter.constraint) { - typeParameterSymbol = getSymbolOfNode(typeParameter); - check(typeParameter.constraint); - } - } function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = type.localTypeParameters; @@ -14292,9 +14600,6 @@ var ts; return type; } function getTypeFromNonGenericTypeReference(node, symbol) { - if (symbol.flags & 262144 && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { - return unknownType; - } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); return unknownType; @@ -14330,9 +14635,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 214: - case 215: + case 216: case 217: + case 219: return declaration; } } @@ -14364,10 +14669,6 @@ var ts; if (arity === void 0) { arity = 0; } return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } - function tryGetGlobalType(name, arity) { - if (arity === void 0) { arity = 0; } - return getTypeOfGlobalSymbol(getGlobalSymbol(name, 793056, undefined), arity); - } function getExportedTypeFromNamespace(namespace, name) { var namespaceSymbol = getGlobalSymbol(namespace, 1536, undefined); var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056); @@ -14468,7 +14769,7 @@ var ts; } function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { - return emptyObjectType; + return emptyUnionType; } var typeSet = []; addTypesToSet(typeSet, types, 16384); @@ -14534,8 +14835,7 @@ var ts; } return links.resolvedType; } - function getStringLiteralType(node) { - var text = node.text; + function getStringLiteralTypeForText(text) { if (ts.hasProperty(stringLiteralTypes, text)) { return stringLiteralTypes[text]; } @@ -14543,17 +14843,17 @@ var ts; type.text = text; return type; } - function getTypeFromStringLiteral(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralType(node); + links.resolvedType = getStringLiteralTypeForText(node.text); } return links.resolvedType; } function getThisType(node) { var container = ts.getThisContainer(node, false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 215)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 217)) { if (!(container.flags & 64) && (container.kind !== 144 || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -14569,6 +14869,22 @@ var ts; } return links.resolvedType; } + function getPredicateType(node) { + return createPredicateType(getSymbolOfNode(node), createTypePredicateFromTypePredicateNode(node)); + } + function createPredicateType(symbol, predicate) { + var type = createType(8 | 134217728); + type.symbol = symbol; + type.predicate = predicate; + return type; + } + function getTypeFromPredicateTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getPredicateType(node); + } + return links.resolvedType; + } function getTypeFromTypeNode(node) { switch (node.kind) { case 117: @@ -14583,15 +14899,15 @@ var ts; return esSymbolType; case 103: return voidType; - case 97: + case 161: return getTypeFromThisTypeNode(node); - case 9: - return getTypeFromStringLiteral(node); + case 162: + return getTypeFromStringLiteralTypeNode(node); case 151: return getTypeFromTypeReference(node); case 150: - return booleanType; - case 188: + return getTypeFromPredicateTypeNode(node); + case 190: return getTypeFromTypeReference(node); case 154: return getTypeFromTypeQueryNode(node); @@ -14669,18 +14985,22 @@ var ts; return t; }; } - function createInferenceMapper(context) { - var mapper = function (t) { - for (var i = 0; i < context.typeParameters.length; i++) { - if (t === context.typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); + function getInferenceMapper(context) { + if (!context.mapper) { + var mapper = function (t) { + var typeParameters = context.typeParameters; + for (var i = 0; i < typeParameters.length; i++) { + if (t === typeParameters[i]) { + context.inferences[i].isFixed = true; + return getInferredType(context, i); + } } - } - return t; - }; - mapper.context = context; - return mapper; + return t; + }; + mapper.context = context; + context.mapper = mapper; + } + return context.mapper; } function identityMapper(type) { return type; @@ -14688,33 +15008,39 @@ var ts; function combineTypeMappers(mapper1, mapper2) { return function (t) { return instantiateType(mapper1(t), mapper2); }; } - function instantiateTypeParameter(typeParameter, mapper) { + function cloneTypeParameter(typeParameter) { var result = createType(512); result.symbol = typeParameter.symbol; - if (typeParameter.constraint) { - result.constraint = instantiateType(typeParameter.constraint, mapper); + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; } else { - result.target = typeParameter; - result.mapper = mapper; + return { + kind: 0, + type: instantiateType(predicate.type, mapper) + }; } - return result; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; - var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } } - if (signature.typePredicate) { - freshTypePredicate = { - parameterName: signature.typePredicate.parameterName, - parameterIndex: signature.typePredicate.parameterIndex, - type: instantiateType(signature.typePredicate.type, mapper) - }; - } - var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -14772,31 +15098,35 @@ var ts; if (type.flags & 32768) { return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); } + if (type.flags & 134217728) { + var predicate = type.predicate; + return createPredicateType(type.symbol, cloneTypePredicate(predicate, mapper)); + } } return type; } function isContextSensitive(node) { ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 173: - case 174: + case 175: + case 176: return isContextSensitiveFunctionLikeDeclaration(node); - case 165: + case 167: return ts.forEach(node.properties, isContextSensitive); - case 164: + case 166: return ts.forEach(node.elements, isContextSensitive); - case 182: + case 184: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 181: + case 183: return node.operatorToken.kind === 52 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 245: + case 247: return isContextSensitive(node.initializer); case 143: case 142: return isContextSensitiveFunctionLikeDeclaration(node); - case 172: + case 174: return isContextSensitive(node.expression); } return false; @@ -14821,7 +15151,7 @@ var ts; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined); } - function compareTypes(source, target) { + function compareTypesIdentical(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined) ? -1 : 0; } function isTypeSubtypeOf(source, target) { @@ -14836,10 +15166,73 @@ var ts; function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } - function isSignatureAssignableTo(source, target) { - var sourceType = getOrCreateTypeFromSignature(source); - var targetType = getOrCreateTypeFromSignature(target); - return checkTypeRelatedTo(sourceType, targetType, assignableRelation, undefined); + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + if (source === target) { + return true; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return false; + } + source = getErasedSignature(source); + target = getErasedSignature(target); + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + for (var i = 0; i < checkCount; i++) { + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + var related = isTypeAssignableTo(t, s) || isTypeAssignableTo(s, t); + if (!related) { + return false; + } + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return true; + } + var sourceReturnType = getReturnTypeOfSignature(source); + if (targetReturnType.flags & 134217728 && targetReturnType.predicate.kind === 1) { + if (!(sourceReturnType.flags & 134217728)) { + return false; + } + } + return isTypeAssignableTo(sourceReturnType, targetReturnType); + } + return true; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, undefined)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; @@ -14894,6 +15287,11 @@ var ts; return -1; if (source.flags & 128 && target === numberType) return -1; + if (source.flags & 128 && target.flags & 128) { + if (result = enumRelatedTo(source, target)) { + return result; + } + } if (source.flags & 256 && target === stringType) return -1; if (relation === assignableRelation) { @@ -14902,6 +15300,36 @@ var ts; if (source === numberType && target.flags & 128) return -1; } + if (source.flags & 8 && target.flags & 8) { + if (source.flags & 134217728 && target.flags & 134217728) { + var sourcePredicate = source; + var targetPredicate = target; + if (sourcePredicate.predicate.kind !== targetPredicate.predicate.kind) { + if (reportErrors) { + reportError(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return 0; + } + if (sourcePredicate.predicate.kind === 1) { + var sourceIdentifierPredicate = sourcePredicate.predicate; + var targetIdentifierPredicate = targetPredicate.predicate; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return 0; + } + } + var related = isRelatedTo(sourcePredicate.predicate.type, targetPredicate.predicate.type, reportErrors, headMessage); + if (related === 0 && reportErrors) { + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return related; + } + return -1; + } if (source.flags & 1048576) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -14977,9 +15405,6 @@ var ts; } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 512 && target.flags & 512) { - return typeParameterIdenticalTo(source, target); - } if (source.flags & 16384 && target.flags & 16384 || source.flags & 32768 && target.flags & 32768) { if (result = eachTypeRelatedToSomeType(source, target)) { @@ -15088,8 +15513,9 @@ var ts; if (sources.length !== targets.length && relation === identityRelation) { return 0; } + var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1; - for (var i = 0; i < targets.length; i++) { + for (var i = 0; i < length; i++) { var related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return 0; @@ -15098,23 +15524,17 @@ var ts; } return result; } - function typeParameterIdenticalTo(source, target) { - if (source.constraint === target.constraint) { - return -1; - } - if (source.constraint === noConstraintType || target.constraint === noConstraintType) { - return 0; - } - return isIdenticalTo(source.constraint, target.constraint); - } - function objectTypeRelatedTo(apparentSource, originalSource, target, reportErrors) { + function objectTypeRelatedTo(source, originalSource, target, reportErrors) { if (overflow) { return 0; } - var id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { - if (!elaborateErrors || (related === 3)) { + if (elaborateErrors && related === 2) { + relation[id] = 3; + } + else { return related === 1 ? -1 : 0; } } @@ -15135,13 +15555,13 @@ var ts; maybeStack = []; expandingFlags = 0; } - sourceStack[depth] = apparentSource; + sourceStack[depth] = source; targetStack[depth] = target; maybeStack[depth] = {}; maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; @@ -15150,15 +15570,15 @@ var ts; result = 1; } else { - result = propertiesRelatedTo(apparentSource, target, reportErrors); + result = propertiesRelatedTo(source, target, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 0, reportErrors); + result &= signaturesRelatedTo(source, target, 0, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 1, reportErrors); + result &= signaturesRelatedTo(source, target, 1, reportErrors); if (result) { - result &= stringIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= stringIndexTypesRelatedTo(source, originalSource, target, reportErrors); if (result) { - result &= numberIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= numberIndexTypesRelatedTo(source, originalSource, target, reportErrors); } } } @@ -15280,61 +15700,38 @@ var ts; } var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 && sourceSignatures.length && targetSignatures.length && + isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0; + } var result = -1; var saveErrorInfo = errorInfo; - if (kind === 1) { - var sourceSig = sourceSignatures[0]; - var targetSig = targetSignatures[0]; - result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); - if (result !== -1) { - return result; - } - } outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; if (!t.hasStringLiterals || target.flags & 262144) { - var localErrors = reportErrors; - var checkedAbstractAssignability = false; + var shouldElaborateErrors = reportErrors; for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { var s = sourceSignatures_1[_a]; if (!s.hasStringLiterals || source.flags & 262144) { - var related = signatureRelatedTo(s, t, localErrors); + var related = signatureRelatedTo(s, t, shouldElaborateErrors); if (related) { result &= related; errorInfo = saveErrorInfo; continue outer; } - localErrors = false; + shouldElaborateErrors = false; } } + if (shouldElaborateErrors && !isPrimitiveApparentType(source)) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } return 0; } } return result; - function abstractSignatureRelatedTo(source, sourceSig, target, targetSig) { - if (sourceSig && targetSig) { - var sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); - var targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); - if (!sourceDecl) { - return -1; - } - var sourceErasedSignature = getErasedSignature(sourceSig); - var targetErasedSignature = getErasedSignature(targetSig); - var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); - var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); - var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); - var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128; - if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0; - } - } - return -1; - } } function signatureRelatedTo(source, target, reportErrors) { if (source === target) { @@ -15382,37 +15779,19 @@ var ts; } result &= related; } - if (source.typePredicate && target.typePredicate) { - var hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; - var hasDifferentTypes; - if (hasDifferentParameterIndex || - (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + if (targetReturnType.flags & 134217728 && targetReturnType.predicate.kind === 1) { + if (!(sourceReturnType.flags & 134217728)) { if (reportErrors) { - var sourceParamText = source.typePredicate.parameterName; - var targetParamText = target.typePredicate.parameterName; - var sourceTypeText = typeToString(source.typePredicate.type); - var targetTypeText = typeToString(target.typePredicate.type); - if (hasDifferentParameterIndex) { - reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceParamText, targetParamText); - } - else if (hasDifferentTypes) { - reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceTypeText, targetTypeText); - } - reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, sourceParamText + " is " + sourceTypeText, targetParamText + " is " + targetTypeText); + reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); } return 0; } } - else if (!source.typePredicate && target.typePredicate) { - if (reportErrors) { - reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); - } - return 0; - } - var targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) - return result; - var sourceReturnType = getReturnTypeOfSignature(source); return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); } function signaturesIdenticalTo(source, target, kind) { @@ -15422,8 +15801,8 @@ var ts; return 0; } var result = -1; - for (var i = 0, len = sourceSignatures.length; i < len; ++i) { - var related = compareSignatures(sourceSignatures[i], targetSignatures[i], false, false, isRelatedTo); + for (var i = 0, len = sourceSignatures.length; i < len; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, isRelatedTo); if (!related) { return 0; } @@ -15503,6 +15882,37 @@ var ts; } return 0; } + function enumRelatedTo(source, target) { + 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)) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + return 0; + } + } + } + return -1; + } + } + function isAbstractConstructorType(type) { + if (type.flags & 65536) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && declaration.flags & 128) { + return true; + } + } + } + return false; } function isDeeplyNestedGeneric(type, stack, depth) { if (type.flags & (4096 | 131072) && depth >= 5) { @@ -15520,7 +15930,7 @@ var ts; return false; } function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypes) !== 0; + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; } function compareProperties(sourceProp, targetProp, compareTypes) { if (sourceProp === targetProp) { @@ -15555,31 +15965,19 @@ var ts; } return false; } - function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + function compareSignaturesIdentical(source, target, partialMatch, ignoreReturnTypes, compareTypes) { if (source === target) { return -1; } if (!(isMatchingSignature(source, target, partialMatch))) { return 0; } - var result = -1; - if (source.typeParameters && target.typeParameters) { - if (source.typeParameters.length !== target.typeParameters.length) { - return 0; - } - for (var i = 0, len = source.typeParameters.length; i < len; ++i) { - var related = compareTypes(source.typeParameters[i], target.typeParameters[i]); - if (!related) { - return 0; - } - result &= related; - } - } - else if (source.typeParameters || target.typeParameters) { + if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) { return 0; } source = getErasedSignature(source); target = getErasedSignature(target); + var result = -1; var targetLen = target.parameters.length; for (var i = 0; i < targetLen; i++) { var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); @@ -15696,10 +16094,13 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); } function getWidenedType(type) { - if (type.flags & 6291456) { + if (type.flags & 140509184) { if (type.flags & (32 | 64)) { return anyType; } + if (type.flags & 134217728) { + return booleanType; + } if (type.flags & 524288) { return getWidenedTypeOfObjectLiteral(type); } @@ -15763,13 +16164,13 @@ var ts; ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 213: + case 215: case 143: case 142: case 145: case 146: - case 173: - case 174: + case 175: + case 176: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -15815,13 +16216,7 @@ var ts; } } function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var unused = typeParameters_1[_i]; - inferences.push({ - primary: undefined, secondary: undefined, isFixed: false - }); - } + var inferences = ts.map(typeParameters, createTypeInferencesObject); return { typeParameters: typeParameters, inferUnionTypes: inferUnionTypes, @@ -15829,6 +16224,13 @@ var ts; inferredTypes: new Array(typeParameters.length) }; } + function createTypeInferencesObject() { + return { + primary: undefined, + secondary: undefined, + isFixed: false + }; + } function inferTypes(context, source, target) { var sourceStack; var targetStack; @@ -15844,6 +16246,21 @@ var ts; return false; } function inferFromTypes(source, target) { + if (source.flags & 16384 && target.flags & 16384 || + source.flags & 32768 && target.flags & 32768) { + var matchingTypes; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (typeIdenticalToSomeType(t, source.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + } + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } if (target.flags & 512) { if (source.flags & 8388608) { return; @@ -15872,6 +16289,11 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } + else if (source.flags & 134217728 && target.flags & 134217728) { + if (source.predicate.kind === target.predicate.kind) { + inferFromTypes(source.predicate.type, target.predicate.type); + } + } else if (source.flags & 8192 && target.flags & 8192 && source.elementTypes.length === target.elementTypes.length) { var sourceTypes = source.elementTypes; var targetTypes = target.elementTypes; @@ -15883,8 +16305,8 @@ var ts; var targetTypes = target.types; var typeParameterCount = 0; var typeParameter; - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var t = targetTypes_2[_i]; + 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)) { typeParameter = t; typeParameterCount++; @@ -15901,15 +16323,16 @@ var ts; } else if (source.flags & 49152) { var sourceTypes = source.types; - for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { - var sourceType = sourceTypes_3[_a]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 && (target.flags & (4096 | 8192) || - (target.flags & 65536) && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { + if (source.flags & 80896 && (target.flags & 4096 && target.typeArguments || + target.flags & 8192 || + target.flags & 65536 && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { if (isInProcess(source, target)) { return; } @@ -15955,14 +16378,7 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - if (source.typePredicate && target.typePredicate) { - if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); - } - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } function inferFromIndexTypes(source, target, sourceKind, targetKind) { var targetIndexType = getIndexTypeOfType(target, targetKind); @@ -15974,6 +16390,25 @@ var ts; } } } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 16384 ? getUnionType(reducedTypes, true) : getIntersectionType(reducedTypes); + } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; @@ -15992,14 +16427,19 @@ var ts; inferredType = emptyObjectType; inferenceSucceeded = true; } + context.inferredTypes[index] = inferredType; if (inferenceSucceeded) { var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); - inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + context.inferredTypes[index] = inferredType = instantiatedConstraint; + } + } } else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { context.failedTypeParameterIndex = index; } - context.inferredTypes[index] = inferredType; } return inferredType; } @@ -16009,9 +16449,6 @@ var ts; } return context.inferredTypes; } - function hasAncestor(node, kind) { - return ts.getAncestor(node, kind) !== undefined; - } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { @@ -16034,21 +16471,6 @@ var ts; } ts.Debug.fail("should not get here"); } - function removeTypesFromUnionType(type, typeKind, isOfTypeKind, allowEmptyUnionResult) { - if (type.flags & 16384) { - var types = type.types; - if (ts.forEach(types, function (t) { return !!(t.flags & typeKind) === isOfTypeKind; })) { - var narrowedType = getUnionType(ts.filter(types, function (t) { return !(t.flags & typeKind) === isOfTypeKind; })); - if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { - return narrowedType; - } - } - } - else if (allowEmptyUnionResult && !!(type.flags & typeKind) === isOfTypeKind) { - return getUnionType(emptyArray); - } - return type; - } function hasInitializer(node) { return !!(node.initializer || ts.isBindingPattern(node.parent) && hasInitializer(node.parent.parent)); } @@ -16066,10 +16488,7 @@ var ts; return links.assignmentChecks[symbol.id] = isAssignedIn(node); function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 56 && node.operatorToken.kind <= 68) { - var n = node.left; - while (n.kind === 172) { - n = n.expression; - } + var n = skipParenthesizedNodes(node.left); if (n.kind === 69 && getResolvedSymbol(n) === symbol) { return true; } @@ -16084,55 +16503,55 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 181: + case 183: return isAssignedInBinaryExpression(node); - case 211: - case 163: - return isAssignedInVariableDeclaration(node); - case 161: - case 162: - case 164: + case 213: case 165: + return isAssignedInVariableDeclaration(node); + case 163: + case 164: case 166: case 167: case 168: case 169: + case 170: case 171: - case 189: - case 172: - case 179: - case 175: - case 178: - case 176: + case 173: + case 191: + case 174: + case 181: case 177: case 180: - case 184: + case 178: + case 179: case 182: - case 185: - case 192: - case 193: + case 186: + case 184: + case 187: + case 194: case 195: - case 196: case 197: case 198: case 199: case 200: case 201: - case 204: - case 205: + case 202: + case 203: case 206: - case 241: - case 242: case 207: case 208: - case 209: + case 243: case 244: - case 233: - case 234: - case 238: - case 239: + case 209: + case 210: + case 211: + case 246: case 235: + case 236: case 240: + case 241: + case 237: + case 242: return ts.forEachChild(node, isAssignedIn); } return false; @@ -16142,53 +16561,66 @@ var ts; var type = getTypeOfSymbol(symbol); if (node && symbol.flags & 3) { if (isTypeAny(type) || type.flags & (80896 | 16384 | 512)) { + var declaration = ts.getDeclarationOfKind(symbol, 213); + var top_1 = declaration && getDeclarationContainer(declaration); + var originalType = type; + var nodeStack = []; loop: while (node.parent) { var child = node; node = node.parent; - var narrowedType = type; switch (node.kind) { - case 196: - if (child !== node.expression) { - narrowedType = narrowType(type, node.expression, child === node.thenStatement); - } + case 198: + case 184: + case 183: + nodeStack.push({ node: node, child: child }); break; - case 182: - if (child !== node.condition) { - narrowedType = narrowType(type, node.condition, child === node.whenTrue); - } - break; - case 181: - if (child === node.right) { - if (node.operatorToken.kind === 51) { - narrowedType = narrowType(type, node.left, true); - } - else if (node.operatorToken.kind === 52) { - narrowedType = narrowType(type, node.left, false); - } - } - break; - case 248: - case 218: - case 213: - case 143: - case 142: - case 145: - case 146: - case 144: + case 250: + case 220: break loop; } - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; - } - type = narrowedType; + if (node === top_1) { + break; } } + var nodes; + while (nodes = nodeStack.pop()) { + var node_1 = nodes.node, child = nodes.child; + switch (node_1.kind) { + case 198: + if (child !== node_1.expression) { + type = narrowType(type, node_1.expression, child === node_1.thenStatement); + } + break; + case 184: + if (child !== node_1.condition) { + type = narrowType(type, node_1.condition, child === node_1.whenTrue); + } + break; + case 183: + if (child === node_1.right) { + if (node_1.operatorToken.kind === 51) { + type = narrowType(type, node_1.left, true); + } + else if (node_1.operatorToken.kind === 52) { + type = narrowType(type, node_1.left, false); + } + } + break; + default: + ts.Debug.fail("Unreachable!"); + } + if (type !== originalType && isVariableAssignedWithin(symbol, node_1)) { + type = originalType; + } + } + if (type === emptyUnionType) { + type = originalType; + } } } return type; function narrowTypeByEquality(type, expr, assumeTrue) { - if (expr.left.kind !== 176 || expr.right.kind !== 9) { + if (expr.left.kind !== 178 || expr.right.kind !== 9) { return type; } var left = expr.left; @@ -16196,24 +16628,30 @@ var ts; if (left.expression.kind !== 69 || getResolvedSymbol(left.expression) !== symbol) { return type; } - var typeInfo = primitiveTypeInfo[right.text]; if (expr.operatorToken.kind === 33) { assumeTrue = !assumeTrue; } - if (assumeTrue) { - if (!typeInfo) { - return removeTypesFromUnionType(type, 258 | 132 | 8 | 16777216, true, false); - } - if (isTypeSubtypeOf(typeInfo.type, type)) { - return typeInfo.type; - } - return removeTypesFromUnionType(type, typeInfo.flags, false, false); + var typeInfo = primitiveTypeInfo[right.text]; + if (typeInfo && typeInfo.type === undefinedType) { + return type; + } + if (!!(type.flags & 1) && typeInfo && assumeTrue) { + return typeInfo.type; + } + var flags; + if (typeInfo) { + flags = typeInfo.flags; } else { - if (typeInfo) { - return removeTypesFromUnionType(type, typeInfo.flags, true, false); - } - return type; + assumeTrue = !assumeTrue; + flags = 132 | 258 | 16777216 | 8; + } + if (!(type.flags & 16384)) { + return filterUnion(type) ? type : emptyUnionType; + } + return getUnionType(ts.filter(type.types, filterUnion), true); + function filterUnion(type) { + return assumeTrue === !!(type.flags & flags); } } function narrowTypeByAnd(type, expr, assumeTrue) { @@ -16223,7 +16661,7 @@ var ts; else { return getUnionType([ narrowType(type, expr.left, false), - narrowType(narrowType(type, expr.left, true), expr.right, false) + narrowType(type, expr.right, false) ]); } } @@ -16231,7 +16669,7 @@ var ts; if (assumeTrue) { return getUnionType([ narrowType(type, expr.left, true), - narrowType(narrowType(type, expr.left, false), expr.right, true) + narrowType(type, expr.right, true) ]); } else { @@ -16267,17 +16705,17 @@ var ts; } } if (targetType) { - if (!assumeTrue) { - if (type.flags & 16384) { - return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, targetType); })); - } - return type; - } - return getNarrowedType(type, targetType); + return getNarrowedType(type, targetType, assumeTrue); } return type; } - function getNarrowedType(originalType, narrowedTypeCandidate) { + function getNarrowedType(originalType, narrowedTypeCandidate, assumeTrue) { + if (!assumeTrue) { + if (originalType.flags & 16384) { + return getUnionType(ts.filter(originalType.types, function (t) { return !isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } if (originalType.flags & 16384) { var assignableConstituents = ts.filter(originalType.types, function (t) { return isTypeAssignableTo(t, narrowedTypeCandidate); }); if (assignableConstituents.length) { @@ -16294,26 +16732,60 @@ var ts; return type; } var signature = getResolvedSignature(expr); - if (signature.typePredicate && - expr.arguments[signature.typePredicate.parameterIndex] && - getSymbolAtLocation(expr.arguments[signature.typePredicate.parameterIndex]) === symbol) { - if (!assumeTrue) { - if (type.flags & 16384) { - return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, signature.typePredicate.type); })); - } - return type; + var predicateType = getReturnTypeOfSignature(signature); + if (!predicateType || !(predicateType.flags & 134217728)) { + return type; + } + var predicate = predicateType.predicate; + if (ts.isIdentifierTypePredicate(predicate)) { + var callExpression = expr; + if (callExpression.arguments[predicate.parameterIndex] && + getSymbolAtTypePredicatePosition(callExpression.arguments[predicate.parameterIndex]) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); } - return getNarrowedType(type, signature.typePredicate.type); + } + else { + var expression = skipParenthesizedNodes(expr.expression); + return narrowTypeByThisTypePredicate(type, predicate, expression, assumeTrue); } return type; } + function narrowTypeByTypePredicateMember(type, expr, assumeTrue) { + if (type.flags & 1) { + return type; + } + var memberType = getTypeOfExpression(expr); + if (!(memberType.flags & 134217728)) { + return type; + } + return narrowTypeByThisTypePredicate(type, memberType.predicate, expr, assumeTrue); + } + function narrowTypeByThisTypePredicate(type, predicate, expression, assumeTrue) { + if (expression.kind === 169 || expression.kind === 168) { + var accessExpression = expression; + var possibleIdentifier = skipParenthesizedNodes(accessExpression.expression); + if (possibleIdentifier.kind === 69 && getSymbolAtTypePredicatePosition(possibleIdentifier) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); + } + } + return type; + } + function getSymbolAtTypePredicatePosition(expr) { + expr = skipParenthesizedNodes(expr); + switch (expr.kind) { + case 69: + case 168: + case 135: + return getSymbolOfEntityNameOrPropertyAccessExpression(expr); + } + } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 168: + case 170: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 172: + case 174: return narrowType(type, expr.expression, assumeTrue); - case 181: + case 183: var operator = expr.operatorToken.kind; if (operator === 32 || operator === 33) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -16328,20 +16800,29 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 179: + case 181: if (expr.operator === 49) { return narrowType(type, expr.operand, !assumeTrue); } break; + case 169: + case 168: + return narrowTypeByTypePredicateMember(type, expr, assumeTrue); } return type; } } + function skipParenthesizedNodes(expression) { + while (expression.kind === 174) { + expression = expression.expression; + } + return expression; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 174) { + if (container.kind === 176) { if (languageVersion < 2) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } @@ -16372,7 +16853,7 @@ var ts; function checkBlockScopedBindingCapturedInLoop(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 244) { + symbol.valueDeclaration.parent.kind === 246) { return; } var container; @@ -16381,11 +16862,11 @@ var ts; } else { container = symbol.valueDeclaration; - while (container.kind !== 212) { + while (container.kind !== 214) { container = container.parent; } container = container.parent; - if (container.kind === 193) { + if (container.kind === 195) { container = container.parent; } } @@ -16415,15 +16896,15 @@ var ts; function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; - if (container.kind === 174) { + if (container.kind === 176) { container = ts.getThisContainer(container, false); needToCaptureLexicalThis = (languageVersion < 2); } switch (container.kind) { - case 218: + case 220: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 217: + case 219: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; case 144: @@ -16448,6 +16929,18 @@ var ts; var symbol = getSymbolOfNode(container.parent); return container.flags & 64 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; } + if (ts.isInJavaScriptFile(node) && container.kind === 175) { + if (ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { + var className = container.parent + .left + .expression + .expression; + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { + return getInferredClassType(classSymbol); + } + } + } return anyType; } function isInConstructorArgumentInitializer(node, constructorDecl) { @@ -16459,50 +16952,64 @@ var ts; return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 168 && node.parent.expression === node; - var classDeclaration = ts.getContainingClass(node); - var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; + var isCallExpression = node.parent.kind === 170 && node.parent.expression === node; var container = ts.getSuperContainer(node, true); var needToCaptureLexicalThis = false; if (!isCallExpression) { - while (container && container.kind === 174) { + while (container && container.kind === 176) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; - if (canUseSuperExpression) { - if ((container.flags & 64) || isCallExpression) { - nodeCheckFlag = 512; - } - else { - nodeCheckFlag = 256; - } - getNodeLinks(node).flags |= nodeCheckFlag; - if (needToCaptureLexicalThis) { - captureLexicalThis(node.parent, container); - } - } - if (!baseClassType) { - if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } if (!canUseSuperExpression) { - if (container && container.kind === 136) { + var current = node; + while (current && current !== container && current.kind !== 136) { + current = current.parent; + } + if (current && current.kind === 136) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 167)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } else { error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); } return unknownType; } + if ((container.flags & 64) || isCallExpression) { + nodeCheckFlag = 512; + } + else { + nodeCheckFlag = 256; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (needToCaptureLexicalThis) { + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 167) { + if (languageVersion < 2) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + return anyType; + } + } + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } if (container.kind === 144 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; @@ -16518,7 +17025,7 @@ var ts; return container.kind === 144; } else { - if (container && ts.isClassLike(container.parent)) { + if (ts.isClassLike(container.parent) || container.parent.kind === 167) { if (container.flags & 64) { return container.kind === 143 || container.kind === 142 || @@ -16629,7 +17136,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 170) { + if (template.parent.kind === 172) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -16649,6 +17156,11 @@ var ts; } return type; } + else if (operator === 51 || operator === 24) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } return undefined; } function applyToContextualType(type, mapper) { @@ -16658,8 +17170,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var current = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -16731,21 +17243,20 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForJsxExpression(expr) { - if (expr.parent.kind === 238) { - var attrib = expr.parent; - var attrsType = getJsxElementAttributesType(attrib.parent); + function getContextualTypeForJsxAttribute(attribute) { + var kind = attribute.kind; + var jsxElement = attribute.parent; + var attrsType = getJsxElementAttributesType(jsxElement); + if (attribute.kind === 240) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } - else { - return getTypeOfPropertyOfType(attrsType, attrib.name.text); - } + return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - if (expr.kind === 239) { - return getJsxElementAttributesType(expr.parent); + else if (attribute.kind === 241) { + return attrsType; } - return undefined; + ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); } function getApparentTypeOfContextualType(node) { var type = getContextualType(node); @@ -16760,39 +17271,41 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 211: + case 213: case 138: case 141: case 140: - case 163: + case 165: return getContextualTypeForInitializerExpression(node); - case 174: - case 204: + case 176: + case 206: return getContextualTypeForReturnExpression(node); - case 184: + case 186: return getContextualTypeForYieldOperand(parent); - case 168: - case 169: - return getContextualTypeForArgument(parent, node); + case 170: case 171: - case 189: + return getContextualTypeForArgument(parent, node); + case 173: + case 191: return getTypeFromTypeNode(parent.type); - case 181: + case 183: return getContextualTypeForBinaryOperand(node); - case 245: + case 247: return getContextualTypeForObjectLiteralElement(parent); - case 164: + case 166: return getContextualTypeForElementExpression(node); - case 182: + case 184: return getContextualTypeForConditionalOperand(node); - case 190: - ts.Debug.assert(parent.parent.kind === 183); + case 192: + ts.Debug.assert(parent.parent.kind === 185); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 172: + case 174: + return getContextualType(parent); + case 242: return getContextualType(parent); case 240: - case 239: - return getContextualTypeForJsxExpression(parent); + case 241: + return getContextualTypeForJsxAttribute(parent); } return undefined; } @@ -16806,7 +17319,7 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 173 || node.kind === 174; + return node.kind === 175 || node.kind === 176; } function getContextualSignatureForFunctionLikeDeclaration(node) { return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) @@ -16826,14 +17339,14 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { signatureList = [signature]; } - else if (!compareSignatures(signatureList[0], signature, false, true, compareTypes)) { + else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, compareTypesIdentical)) { return undefined; } else { @@ -16854,13 +17367,13 @@ var ts; } function isAssignmentTarget(node) { var parent = node.parent; - if (parent.kind === 181 && parent.operatorToken.kind === 56 && parent.left === node) { + if (parent.kind === 183 && parent.operatorToken.kind === 56 && parent.left === node) { return true; } - if (parent.kind === 245) { + if (parent.kind === 247) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 164) { + if (parent.kind === 166) { return isAssignmentTarget(parent); } return false; @@ -16870,8 +17383,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false); } function hasDefaultValue(node) { - return (node.kind === 163 && !!node.initializer) || - (node.kind === 181 && node.operatorToken.kind === 56); + return (node.kind === 165 && !!node.initializer) || + (node.kind === 183 && node.operatorToken.kind === 56); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -16880,7 +17393,7 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 185) { + if (inDestructuringPattern && e.kind === 187) { var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1) || (languageVersion >= 2 ? getElementTypeOfIterable(restArrayType, undefined) : undefined); @@ -16892,7 +17405,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 185; + hasSpreadElement = hasSpreadElement || e.kind === 187; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { @@ -16903,7 +17416,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { var pattern = contextualType.pattern; - if (pattern && (pattern.kind === 162 || pattern.kind === 164)) { + if (pattern && (pattern.kind === 164 || pattern.kind === 166)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -16911,7 +17424,7 @@ var ts; elementTypes.push(contextualType.elementTypes[i]); } else { - if (patternElement.kind !== 187) { + if (patternElement.kind !== 189) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -16957,31 +17470,31 @@ var ts; var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 161 || contextualType.pattern.kind === 165); + (contextualType.pattern.kind === 163 || contextualType.pattern.kind === 167); var typeFlags = 0; var patternWithComputedProperties = false; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 245 || - memberDecl.kind === 246 || + if (memberDecl.kind === 247 || + memberDecl.kind === 248 || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 245) { + if (memberDecl.kind === 247) { type = checkPropertyAssignment(memberDecl, contextualMapper); } else if (memberDecl.kind === 143) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 246); + ts.Debug.assert(memberDecl.kind === 248); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 | 67108864 | member.flags, member.name); if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 245 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 246 && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 247 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 248 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912; } @@ -17060,34 +17573,19 @@ var ts; checkJsxOpeningLikeElement(node); return jsxElementType || anyType; } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 69) { - return lhs.text === rhs.text; - } - return lhs.right.text === rhs.right.text && - tagNamesAreEquivalent(lhs.left, rhs.left); - } function checkJsxElement(node) { checkJsxOpeningLikeElement(node.openingElement); - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - error(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNode(node.openingElement.tagName)); - } - else { - getJsxElementTagSymbol(node.closingElement); - } + getJsxElementTagSymbol(node.closingElement); for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 240: + case 242: checkJsxExpression(child); break; - case 233: + case 235: checkJsxElement(child); break; - case 234: + case 236: checkJsxSelfClosingElement(child); break; } @@ -17155,14 +17653,13 @@ var ts; } return type; } - function getJsxIntrinsicElementsType() { - if (!jsxIntrinsicElementsType) { - jsxIntrinsicElementsType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.IntrinsicElements) || unknownType; + function getJsxType(name) { + if (jsxTypes[name] === undefined) { + return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType; } - return jsxIntrinsicElementsType; + return jsxTypes[name]; } function getJsxElementTagSymbol(node) { - var flags = 8; var links = getNodeLinks(node); if (!links.resolvedSymbol) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -17174,7 +17671,7 @@ var ts; } return links.resolvedSymbol; function lookupIntrinsicTag(node) { - var intrinsicElementsType = getJsxIntrinsicElementsType(); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); if (intrinsicProp) { @@ -17234,12 +17731,7 @@ var ts; return unknownType; } } - var returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); - var elemClassType = getJsxGlobalElementClassType(); - if (elemClassType) { - checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - return returnType; + return getUnionType(signatures.map(getReturnTypeOfSignature)); } function getJsxElementPropertiesName() { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536, undefined); @@ -17268,6 +17760,20 @@ var ts; var sym = getJsxElementTagSymbol(node); if (links.jsxFlags & 4) { var elemInstanceType = getJsxElementInstanceType(node); + var callSignature = getSingleCallSignature(getTypeOfSymbol(sym)); + var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); + var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType) && (paramType.flags & 80896)) { + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return paramType; + } + var elemClassType = getJsxGlobalElementClassType(); + if (elemClassType) { + checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } @@ -17286,12 +17792,29 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return links.resolvedJsxType = attributesType; } - else if (!(attributesType.flags & 80896)) { - error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_must_be_an_object_type, typeToString(attributesType)); + else if (attributesType.flags & 16384) { + error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return links.resolvedJsxType = anyType; } else { - return links.resolvedJsxType = attributesType; + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return links.resolvedJsxType = apparentAttributesType; } } } @@ -17319,7 +17842,7 @@ var ts; return jsxElementClassType; } function getJsxIntrinsicTagNames() { - var intrinsics = getJsxIntrinsicElementsType(); + var intrinsics = getJsxType(JsxNames.IntrinsicElements); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } function checkJsxPreconditions(errorNode) { @@ -17335,21 +17858,21 @@ var ts; function checkJsxOpeningLikeElement(node) { checkGrammarJsxElement(node); checkJsxPreconditions(node); - if (compilerOptions.jsx === 2) { - var reactSym = resolveName(node.tagName, "React", 107455, ts.Diagnostics.Cannot_find_name_0, "React"); - if (reactSym) { - getSymbolLinks(reactSym).referenced = true; - } + var reactRefErr = compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); + if (reactSym) { + getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = {}; var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 238) { + if (node.attributes[i].kind === 240) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 239); + ts.Debug.assert(node.attributes[i].kind === 241); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -17384,10 +17907,10 @@ var ts; var flags = getDeclarationFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (left.kind === 95) { - var errorNode = node.kind === 166 ? + var errorNode = node.kind === 168 ? node.name : node.right; - if (getDeclarationKindFromSymbol(prop) !== 143) { + if (languageVersion < 2 && getDeclarationKindFromSymbol(prop) !== 143) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } @@ -17456,7 +17979,7 @@ var ts; return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 166 + var left = node.kind === 168 ? node.expression : node.left; var type = checkExpression(left); @@ -17471,7 +17994,7 @@ var ts; function checkIndexedAccess(node) { if (!node.argumentExpression) { var sourceFile = getSourceFile(node); - if (node.parent.kind === 169 && node.parent.expression === node) { + if (node.parent.kind === 171 && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -17530,7 +18053,7 @@ var ts; if (indexArgumentExpression.kind === 9 || indexArgumentExpression.kind === 8) { return indexArgumentExpression.text; } - if (indexArgumentExpression.kind === 167 || indexArgumentExpression.kind === 166) { + if (indexArgumentExpression.kind === 169 || indexArgumentExpression.kind === 168) { var value = getConstantValue(indexArgumentExpression); if (value !== undefined) { return value.toString(); @@ -17573,7 +18096,7 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 170) { + if (node.kind === 172) { checkExpression(node.template); } else if (node.kind !== 139) { @@ -17627,7 +18150,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 185) { + if (arg && arg.kind === 187) { return i; } } @@ -17639,11 +18162,11 @@ var ts; var callIsIncomplete; var isDecorator; var spreadArgIndex = -1; - if (node.kind === 170) { + if (node.kind === 172) { var tagExpression = node; adjustedArgCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 183) { + if (tagExpression.template.kind === 185) { var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -17663,7 +18186,7 @@ var ts; else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 169); + ts.Debug.assert(callExpression.kind === 171); return signature.minArgumentCount === 0; } adjustedArgCount = callExpression.arguments.hasTrailingComma ? args.length + 1 : args.length; @@ -17704,7 +18227,7 @@ var ts; } function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; - var inferenceMapper = createInferenceMapper(context); + var inferenceMapper = getInferenceMapper(context); for (var i = 0; i < typeParameters.length; i++) { if (!context.inferences[i].isFixed) { context.inferredTypes[i] = undefined; @@ -17716,7 +18239,7 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 187) { + if (arg === undefined || arg.kind !== 189) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { @@ -17737,13 +18260,11 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; + var mapper; for (var i = 0; i < typeParameters.length; i++) { - var typeArgNode = typeArguments[i]; - var typeArgument = getTypeFromTypeNode(typeArgNode); - typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { @@ -17753,7 +18274,11 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); typeArgumentHeadMessage = headMessage; } - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); } } } @@ -17763,12 +18288,12 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 187) { + if (arg === undefined || arg.kind !== 189) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { argType = arg.kind === 9 && !reportErrors - ? getStringLiteralType(arg) + ? getStringLiteralTypeForText(arg.text) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; @@ -17782,10 +18307,10 @@ var ts; } function getEffectiveCallArguments(node) { var args; - if (node.kind === 170) { + if (node.kind === 172) { var template = node.template; args = [undefined]; - if (template.kind === 183) { + if (template.kind === 185) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); @@ -17802,8 +18327,8 @@ var ts; function getEffectiveArgumentCount(node, args, signature) { if (node.kind === 139) { switch (node.parent.kind) { - case 214: - case 186: + case 216: + case 188: return 1; case 141: return 2; @@ -17823,7 +18348,7 @@ var ts; } } function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 216) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } @@ -17844,7 +18369,7 @@ var ts; return unknownType; } function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 216) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } @@ -17863,7 +18388,7 @@ var ts; case 69: case 8: case 9: - return getStringLiteralType(element.name); + return getStringLiteralTypeForText(element.name.text); case 136: var nameType = checkComputedPropertyName(element.name); if (allConstituentTypesHaveKind(nameType, 16777216)) { @@ -17881,7 +18406,7 @@ var ts; return unknownType; } function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 216) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } @@ -17918,14 +18443,14 @@ var ts; if (node.kind === 139) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 170) { + else if (argIndex === 0 && node.kind === 172) { return globalTemplateStringsArrayType; } return undefined; } function getEffectiveArgument(node, args, argIndex) { if (node.kind === 139 || - (argIndex === 0 && node.kind === 170)) { + (argIndex === 0 && node.kind === 172)) { return undefined; } return args[argIndex]; @@ -17934,7 +18459,7 @@ var ts; if (node.kind === 139) { return node.expression; } - else if (argIndex === 0 && node.kind === 170) { + else if (argIndex === 0 && node.kind === 172) { return node.template; } else { @@ -17942,7 +18467,7 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 170; + var isTaggedTemplate = node.kind === 172; var isDecorator = node.kind === 139; var typeArguments; if (!isTaggedTemplate && !isDecorator) { @@ -17990,7 +18515,8 @@ var ts; } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true, headMessage); + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -18042,7 +18568,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { @@ -18174,8 +18700,8 @@ var ts; } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 214: - case 186: + case 216: + case 188: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; case 138: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; @@ -18211,13 +18737,13 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 168) { + if (node.kind === 170) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 169) { + else if (node.kind === 171) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 170) { + else if (node.kind === 172) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } else if (node.kind === 139) { @@ -18229,19 +18755,30 @@ var ts; } return links.resolvedSignature; } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined); + } + return links.inferredClassType; + } function checkCallExpression(node) { checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 95) { return voidType; } - if (node.kind === 169) { + if (node.kind === 171) { var declaration = signature.declaration; if (declaration && declaration.kind !== 144 && declaration.kind !== 148 && declaration.kind !== 153) { - if (compilerOptions.noImplicitAny) { + var funcSymbol = checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16)) { + return getInferredClassType(funcSymbol); + } + else if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; @@ -18290,7 +18827,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187) { + if (element.kind !== 189) { if (element.name.kind === 69) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -18324,7 +18861,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 192) { + if (func.body.kind !== 194) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -18429,22 +18966,29 @@ var ts; if (returnType === voidType || isTypeAny(returnType)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 || !(func.flags & 524288)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 194 || !(func.flags & 524288)) { return; } - if (func.flags & 1048576) { - if (compilerOptions.noImplicitReturns) { - error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { + var hasExplicitReturn = func.flags & 1048576; + if (returnType && !hasExplicitReturn) { error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + var inferredReturnType = hasExplicitReturn + ? getReturnTypeOfSignature(getSignatureFromDeclaration(func)) + : voidType; + if (inferredReturnType === voidType || isTypeAny(inferredReturnType)) { + return; + } + } + error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 173) { + if (!hasGrammarError && node.kind === 175) { checkGrammarForGenerator(node); } if (contextualMapper === identityMapper && isContextSensitive(node)) { @@ -18477,6 +19021,7 @@ var ts; } if (!contextChecked) { checkSignatureDeclaration(node); + checkNodeDeferred(node); } } } @@ -18486,39 +19031,34 @@ var ts; } return type; } - function checkFunctionExpressionOrObjectLiteralMethodBody(node) { + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; } - var returnType = node.type && getTypeFromTypeNode(node.type); - var promisedType; - if (returnType && isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - if (returnType && !node.asteriskToken) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + if (!node.asteriskToken) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { if (!node.type) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 192) { + if (node.body.kind === 194) { checkSourceElement(node.body); } else { var exprType = checkExpression(node.body); - if (returnType) { + if (returnOrPromisedType) { if (isAsync) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); - checkTypeAssignableTo(awaitedType, promisedType, node.body); + checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } else { - checkTypeAssignableTo(exprType, returnType, node.body); + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } - checkFunctionAndClassExpressionBodies(node.body); } } } @@ -18540,13 +19080,13 @@ var ts; var symbol = findSymbol(n); return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 3) !== 0; } - case 166: { + case 168: { var symbol = findSymbol(n); return !symbol || symbol === unknownSymbol || (symbol.flags & ~8) !== 0; } - case 167: + case 169: return true; - case 172: + case 174: return isReferenceOrErrorExpression(n.expression); default: return false; @@ -18555,11 +19095,11 @@ var ts; function isConstVariableReference(n) { switch (n.kind) { case 69: - case 166: { + case 168: { var symbol = findSymbol(n); return symbol && (symbol.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384) !== 0; } - case 167: { + case 169: { var index = n.argumentExpression; var symbol = findSymbol(n.expression); if (symbol && index && index.kind === 9) { @@ -18569,7 +19109,7 @@ var ts; } return false; } - case 172: + case 174: return isConstVariableReference(n.expression); default: return false; @@ -18645,8 +19185,8 @@ var ts; } if (type.flags & 49152) { 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_10 = types; _i < types_10.length; _i++) { + var current = types_10[_i]; if (current.flags & kind) { return true; } @@ -18661,8 +19201,8 @@ var ts; } if (type.flags & 49152) { var types = type.types; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var current = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var current = types_11[_i]; if (!(current.flags & kind)) { return false; } @@ -18699,7 +19239,7 @@ var ts; var properties = node.properties; for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var p = properties_3[_i]; - if (p.kind === 245 || p.kind === 246) { + if (p.kind === 247 || p.kind === 248) { var name_13 = p.name; if (name_13.kind === 136) { checkComputedPropertyName(name_13); @@ -18714,7 +19254,7 @@ var ts; isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1) || getIndexTypeOfType(sourceType, 0); if (type) { - if (p.kind === 246) { + if (p.kind === 248) { checkDestructuringAssignment(p, type); } else { @@ -18736,8 +19276,8 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187) { - if (e.kind !== 185) { + if (e.kind !== 189) { + if (e.kind !== 187) { var propName = "" + i; var type = isTypeAny(sourceType) ? sourceType @@ -18762,7 +19302,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 181 && restExpression.operatorToken.kind === 56) { + if (restExpression.kind === 183 && restExpression.operatorToken.kind === 56) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -18776,7 +19316,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 246) { + if (exprOrAssignment.kind === 248) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -18786,14 +19326,14 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 181 && target.operatorToken.kind === 56) { + if (target.kind === 183 && target.operatorToken.kind === 56) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 165) { + if (target.kind === 167) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 164) { + if (target.kind === 166) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); @@ -18810,7 +19350,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 && (left.kind === 165 || left.kind === 164)) { + if (operator === 56 && (left.kind === 167 || left.kind === 166)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); @@ -19009,7 +19549,7 @@ var ts; function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { - return getStringLiteralType(node); + return getStringLiteralTypeForText(node.text); } return stringType; } @@ -19072,8 +19612,8 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 166 && node.parent.expression === node) || - (node.parent.kind === 167 && node.parent.expression === node) || + var ok = (node.parent.kind === 168 && node.parent.expression === node) || + (node.parent.kind === 169 && node.parent.expression === node) || ((node.kind === 69 || node.kind === 135) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); @@ -19100,7 +19640,7 @@ var ts; return booleanType; case 8: return checkNumericLiteral(node); - case 183: + case 185: return checkTemplateExpression(node); case 9: return checkStringLiteralExpression(node); @@ -19108,58 +19648,58 @@ var ts; return stringType; case 10: return globalRegExpType; - case 164: - return checkArrayLiteral(node, contextualMapper); - case 165: - return checkObjectLiteral(node, contextualMapper); case 166: - return checkPropertyAccessExpression(node); + return checkArrayLiteral(node, contextualMapper); case 167: - return checkIndexedAccess(node); + return checkObjectLiteral(node, contextualMapper); case 168: + return checkPropertyAccessExpression(node); case 169: - return checkCallExpression(node); + return checkIndexedAccess(node); case 170: - return checkTaggedTemplateExpression(node); - case 172: - return checkExpression(node.expression, contextualMapper); - case 186: - return checkClassExpression(node); - case 173: - case 174: - return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 176: - return checkTypeOfExpression(node); case 171: - case 189: - return checkAssertion(node); + return checkCallExpression(node); + case 172: + return checkTaggedTemplateExpression(node); + case 174: + return checkExpression(node.expression, contextualMapper); + case 188: + return checkClassExpression(node); case 175: - return checkDeleteExpression(node); - case 177: - return checkVoidExpression(node); + case 176: + return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); case 178: - return checkAwaitExpression(node); + return checkTypeOfExpression(node); + case 173: + case 191: + return checkAssertion(node); + case 177: + return checkDeleteExpression(node); case 179: - return checkPrefixUnaryExpression(node); + return checkVoidExpression(node); case 180: - return checkPostfixUnaryExpression(node); + return checkAwaitExpression(node); case 181: - return checkBinaryExpression(node, contextualMapper); + return checkPrefixUnaryExpression(node); case 182: - return checkConditionalExpression(node, contextualMapper); - case 185: - return checkSpreadElementExpression(node, contextualMapper); - case 187: - return undefinedType; + return checkPostfixUnaryExpression(node); + case 183: + return checkBinaryExpression(node, contextualMapper); case 184: + return checkConditionalExpression(node, contextualMapper); + case 187: + return checkSpreadElementExpression(node, contextualMapper); + case 189: + return undefinedType; + case 186: return checkYieldExpression(node); - case 240: + case 242: return checkJsxExpression(node); - case 233: - return checkJsxElement(node); - case 234: - return checkJsxSelfClosingElement(node); case 235: + return checkJsxElement(node); + case 236: + return checkJsxSelfClosingElement(node); + case 237: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -19169,8 +19709,8 @@ var ts; grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } checkSourceElement(node.constraint); + getConstraintOfTypeParameter(getDeclaredTypeOfTypeParameter(getSymbolOfNode(node))); if (produceDiagnostics) { - checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } @@ -19196,8 +19736,8 @@ var ts; return false; } return node.kind === 143 || - node.kind === 213 || - node.kind === 173; + node.kind === 215 || + node.kind === 175; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { @@ -19211,12 +19751,12 @@ var ts; } return -1; } - function isInLegalTypePredicatePosition(node) { + function isInLegalParameterTypePredicatePosition(node) { switch (node.parent.kind) { - case 174: + case 176: case 147: - case 213: - case 173: + case 215: + case 175: case 152: case 143: case 142: @@ -19224,11 +19764,23 @@ var ts; } return false; } + function isInLegalThisTypePredicatePosition(node) { + if (isInLegalParameterTypePredicatePosition(node)) { + return true; + } + switch (node.parent.kind) { + case 141: + case 140: + case 145: + return node === node.parent.type; + } + return false; + } function checkSignatureDeclaration(node) { if (node.kind === 149) { checkGrammarIndexSignature(node); } - else if (node.kind === 152 || node.kind === 213 || node.kind === 153 || + else if (node.kind === 152 || node.kind === 215 || node.kind === 153 || node.kind === 147 || node.kind === 144 || node.kind === 148) { checkGrammarFunctionLikeDeclaration(node); @@ -19237,9 +19789,14 @@ var ts; ts.forEach(node.parameters, checkParameter); if (node.type) { if (node.type.kind === 150) { - var typePredicate = getSignatureFromDeclaration(node).typePredicate; + var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + if (!returnType || !(returnType.flags & 134217728)) { + return; + } + var typePredicate = returnType.predicate; var typePredicateNode = node.type; - if (isInLegalTypePredicatePosition(typePredicateNode)) { + checkSourceElement(typePredicateNode); + if (ts.isIdentifierTypePredicate(typePredicate)) { if (typePredicate.parameterIndex >= 0) { if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); @@ -19255,8 +19812,8 @@ var ts; if (hasReportedError) { break; } - if (param.name.kind === 161 || - param.name.kind === 162) { + if (param.name.kind === 163 || + param.name.kind === 164) { (function checkBindingPattern(pattern) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; @@ -19266,8 +19823,8 @@ var ts; hasReportedError = true; break; } - else if (element.name.kind === 162 || - element.name.kind === 161) { + else if (element.name.kind === 164 || + element.name.kind === 163) { checkBindingPattern(element.name); } } @@ -19279,9 +19836,6 @@ var ts; } } } - else { - error(typePredicateNode, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); - } } else { checkSourceElement(node.type); @@ -19316,7 +19870,7 @@ var ts; checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 215) { + if (node.kind === 217) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -19358,7 +19912,7 @@ var ts; } function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); - checkFunctionLikeDeclaration(node); + checkFunctionOrMethodDeclaration(node); if (node.flags & 128 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } @@ -19379,7 +19933,7 @@ var ts; return; } function isSuperCallExpression(n) { - return n.kind === 168 && n.expression.kind === 95; + return n.kind === 170 && n.expression.kind === 95; } function containsSuperCallAsComputedPropertyName(n) { return n.name && containsSuperCall(n.name); @@ -19400,7 +19954,7 @@ var ts; if (n.kind === 97) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 173 && n.kind !== 213) { + else if (n.kind !== 175 && n.kind !== 215) { ts.forEachChild(n, markThisReferencesAsErrors); } } @@ -19425,7 +19979,7 @@ var ts; var superCallStatement; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 195 && isSuperCallExpression(statement.expression)) { + if (statement.kind === 197 && isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; } @@ -19449,6 +20003,8 @@ var ts; function checkAccessorDeclaration(node) { if (produceDiagnostics) { checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); if (node.kind === 145) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288)) { if (node.flags & 1048576) { @@ -19461,6 +20017,9 @@ var ts; } } } + if (node.name.kind === 136) { + checkComputedPropertyName(node.name); + } if (!ts.hasDynamicName(node)) { var otherKind = node.kind === 145 ? 146 : 145; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); @@ -19479,18 +20038,32 @@ var ts; } getTypeOfAccessors(getSymbolOfNode(node)); } - checkFunctionLikeDeclaration(node); + if (node.parent.kind !== 167) { + checkSourceElement(node.body); + } + else { + checkNodeDeferred(node); + } + } + function checkAccessorDeferred(node) { + checkSourceElement(node.body); } function checkMissingDeclaration(node) { checkDecorators(node); } - function checkTypeArgumentConstraints(typeParameters, typeArguments) { + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var typeArguments; + var mapper; var result = true; for (var i = 0; i < typeParameters.length; i++) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { + if (!typeArguments) { + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + mapper = createTypeMapper(typeParameters, typeArguments); + } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; @@ -19547,7 +20120,7 @@ var ts; return; } var signaturesToCheck; - if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 215) { + if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 217) { ts.Debug.assert(signatureDeclarationNode.kind === 147 || signatureDeclarationNode.kind === 148); var signatureKind = signatureDeclarationNode.kind === 147 ? 0 : 1; var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); @@ -19559,7 +20132,7 @@ var ts; } for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { var otherSignature = signaturesToCheck_1[_i]; - if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { + if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature, false)) { return; } } @@ -19567,9 +20140,9 @@ var ts; } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedNodeFlags(n); - if (n.parent.kind !== 215 && - n.parent.kind !== 214 && - n.parent.kind !== 186 && + if (n.parent.kind !== 217 && + n.parent.kind !== 216 && + n.parent.kind !== 188 && ts.isInAmbientContext(n)) { if (!(flags & 4)) { flags |= 2; @@ -19642,14 +20215,16 @@ var ts; seen = c === node; } }); - if (subsequentNode) { + if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - ts.Debug.assert(node.kind === 143 || node.kind === 142); - ts.Debug.assert((node.flags & 64) !== (subsequentNode.flags & 64)); - var diagnostic = node.flags & 64 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); + var reportError = (node.kind === 143 || node.kind === 142) && + (node.flags & 64) !== (subsequentNode.flags & 64); + if (reportError) { + var diagnostic = node.flags & 64 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } return; } else if (ts.nodeIsPresent(subsequentNode.body)) { @@ -19678,11 +20253,11 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 215 || node.parent.kind === 155 || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 217 || node.parent.kind === 155 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 213 || node.kind === 143 || node.kind === 142 || node.kind === 144) { + if (node.kind === 215 || node.kind === 143 || node.kind === 142 || node.kind === 144) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -19736,7 +20311,7 @@ var ts; if (!bodySignature.hasStringLiterals) { for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { var signature = signatures_3[_a]; - if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { + if (!signature.hasStringLiterals && !isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; } @@ -19795,16 +20370,16 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 215: + case 217: return 2097152; - case 218: + case 220: return d.name.kind === 9 || ts.getModuleInstanceState(d) !== 0 ? 4194304 | 1048576 : 4194304; - case 214: - case 217: + case 216: + case 219: return 2097152 | 1048576; - case 221: + case 223: var result = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); @@ -19911,15 +20486,16 @@ var ts; error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } + checkReturnTypeAnnotationAsExpression(node); var promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } var promiseName = ts.getEntityNameFromTypeNode(node.type); - var root = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, root.text, 107455); + var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); + var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455); if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, getFullyQualifiedName(promiseConstructor)); + error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); return unknownType; } return checkAwaitedType(promiseType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); @@ -19934,7 +20510,7 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 214: + case 216: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); @@ -19971,23 +20547,10 @@ var ts; } } function checkTypeAnnotationAsExpression(node) { - switch (node.kind) { - case 141: - checkTypeNodeAsExpression(node.type); - break; - case 138: - checkTypeNodeAsExpression(node.type); - break; - case 143: - checkTypeNodeAsExpression(node.type); - break; - case 145: - checkTypeNodeAsExpression(node.type); - break; - case 146: - checkTypeNodeAsExpression(ts.getSetAccessorTypeAnnotationNode(node)); - break; - } + checkTypeNodeAsExpression(node.type); + } + function checkReturnTypeAnnotationAsExpression(node) { + checkTypeNodeAsExpression(node.type); } function checkParameterTypeAnnotationsAsExpressions(node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -20007,16 +20570,18 @@ var ts; } if (compilerOptions.emitDecoratorMetadata) { switch (node.kind) { - case 214: + case 216: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; case 143: - checkParameterTypeAnnotationsAsExpressions(node); - case 146: case 145: + case 146: + checkParameterTypeAnnotationsAsExpressions(node); + checkReturnTypeAnnotationAsExpression(node); + break; case 141: case 138: checkTypeAnnotationAsExpression(node); @@ -20031,13 +20596,13 @@ var ts; } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); + checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); } } - function checkFunctionLikeDeclaration(node) { + function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); var isAsync = ts.isAsyncFunctionLike(node); @@ -20050,7 +20615,8 @@ var ts; if (!ts.hasDynamicName(node)) { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.getDeclarationOfKind(localSymbol, node.kind); + var firstDeclaration = ts.forEach(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(getSourceFile(declaration)) ? + declaration : undefined; }); if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); } @@ -20061,13 +20627,9 @@ var ts; } } checkSourceElement(node.body); - if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { - var returnType = getTypeFromTypeNode(node.type); - var promisedType; - if (isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + if (!node.asteriskToken) { + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !node.type) { if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { @@ -20079,13 +20641,10 @@ var ts; } } function checkBlock(node) { - if (node.kind === 192) { + if (node.kind === 194) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 219) { - checkFunctionAndClassExpressionBodies(node); - } } function checkCollisionWithArgumentsInGeneratedCode(node) { if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { @@ -20161,11 +20720,11 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 218 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 220 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 248 && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 250 && ts.isExternalOrCommonJsModule(parent)) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -20173,7 +20732,7 @@ var ts; if ((ts.getCombinedNodeFlags(node) & 24576) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 211 && !node.initializer) { + if (node.kind === 213 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -20183,15 +20742,15 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212); - var container = varDeclList.parent.kind === 193 && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 214); + var container = varDeclList.parent.kind === 195 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 192 && ts.isFunctionLike(container.parent) || - container.kind === 219 || - container.kind === 218 || - container.kind === 248); + (container.kind === 194 && ts.isFunctionLike(container.parent) || + container.kind === 221 || + container.kind === 220 || + container.kind === 250); if (!namesShareScope) { var name_14 = symbolToString(localDeclarationSymbol); error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_14, name_14); @@ -20236,7 +20795,7 @@ var ts; checkExpressionCached(node.initializer); } } - if (node.kind === 163) { + if (node.kind === 165) { if (node.propertyName && node.propertyName.kind === 136) { checkComputedPropertyName(node.propertyName); } @@ -20274,7 +20833,7 @@ var ts; } if (node.kind !== 141 && node.kind !== 140) { checkExportsOnMergedDeclarations(node); - if (node.kind === 211 || node.kind === 163) { + if (node.kind === 213 || node.kind === 165) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -20295,7 +20854,7 @@ var ts; ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 165) { + if (node.modifiers && node.parent.kind === 167) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -20314,7 +20873,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 194) { + if (node.thenStatement.kind === 196) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -20331,12 +20890,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 212) { + if (node.initializer && node.initializer.kind === 214) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 212) { + if (node.initializer.kind === 214) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -20351,13 +20910,13 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 214) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); - if (varExpr.kind === 164 || varExpr.kind === 165) { + if (varExpr.kind === 166 || varExpr.kind === 167) { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { @@ -20372,7 +20931,7 @@ var ts; } function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 214) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -20382,7 +20941,7 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 164 || varExpr.kind === 165) { + if (varExpr.kind === 166 || varExpr.kind === 167) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258)) { @@ -20510,7 +21069,13 @@ var ts; } function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); - var arrayType = removeTypesFromUnionType(arrayOrStringType, 258, true, true); + var arrayType = arrayOrStringType; + if (arrayOrStringType.flags & 16384) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258); })); + } + else if (arrayOrStringType.flags & 258) { + arrayType = emptyUnionType; + } var hasStringConstituent = arrayOrStringType !== arrayType; var reportedError = false; if (hasStringConstituent) { @@ -20570,7 +21135,7 @@ var ts; error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { + else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || returnType.flags & 134217728) { if (ts.isAsyncFunctionLike(func)) { var promisedType = getPromisedType(returnType); var awaitedType = checkAwaitedType(exprType, node.expression, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -20601,7 +21166,7 @@ var ts; var expressionType = checkExpression(node.expression); var expressionTypeIsStringLike = someConstituentTypeHasKind(expressionType, 258); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 242 && !hasDuplicateDefaultClause) { + if (clause.kind === 244 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -20613,13 +21178,12 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 241) { + if (produceDiagnostics && clause.kind === 243) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); - if (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258)) { - return; - } - if (!isTypeAssignableTo(expressionType, caseType)) { + var expressionTypeIsAssignableToCaseType = (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258)) || + isTypeAssignableTo(expressionType, caseType); + if (!expressionTypeIsAssignableToCaseType) { checkTypeAssignableTo(caseType, expressionType, caseClause.expression, undefined); } } @@ -20633,7 +21197,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 207 && current.label.text === node.label.text) { + if (current.kind === 209 && current.label.text === node.label.text) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; @@ -20773,8 +21337,12 @@ var ts; } function checkClassExpression(node) { checkClassLikeDeclaration(node); + checkNodeDeferred(node); return getTypeOfSymbol(getSymbolOfNode(node)); } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + } function checkClassDeclaration(node) { if (!node.name && !(node.flags & 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -20872,7 +21440,7 @@ var ts; if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(derivedClassDecl.flags & 128))) { - if (derivedClassDecl.kind === 186) { + if (derivedClassDecl.kind === 188) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -20982,7 +21550,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 215); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 217); if (symbol.declarations.length > 1) { if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { error(node.name, ts.Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); @@ -21047,7 +21615,8 @@ var ts; error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); } if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue++; + getNodeLinks(member).enumMemberValue = autoValue; + autoValue++; } } nodeLinks.flags |= 8192; @@ -21079,7 +21648,7 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 179: + case 181: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; @@ -21090,7 +21659,7 @@ var ts; case 50: return ~value_1; } return undefined; - case 181: + case 183: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -21115,11 +21684,11 @@ var ts; return undefined; case 8: return +e.text; - case 172: + case 174: return evalConstant(e.expression); case 69: - case 167: - case 166: + case 169: + case 168: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; @@ -21130,7 +21699,7 @@ var ts; } else { var expression; - if (e.kind === 167) { + if (e.kind === 169) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9) { return undefined; @@ -21147,7 +21716,7 @@ var ts; if (current.kind === 69) { break; } - else if (current.kind === 166) { + else if (current.kind === 168) { current = current.expression; } else { @@ -21206,7 +21775,7 @@ var ts; } var seenEnumMissingInitialInitializer = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 217) { + if (declaration.kind !== 219) { return false; } var enumDeclaration = declaration; @@ -21229,8 +21798,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 214 || - (declaration.kind === 213 && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 216 || + (declaration.kind === 215 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -21281,7 +21850,7 @@ var ts; error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); } } - var mergedClass = ts.getDeclarationOfKind(symbol, 214); + var mergedClass = ts.getDeclarationOfKind(symbol, 216); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768; @@ -21303,7 +21872,7 @@ var ts; if (node.kind === 135) { node = node.left; } - else if (node.kind === 166) { + else if (node.kind === 168) { node = node.expression; } else { @@ -21319,9 +21888,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 219 && node.parent.parent.name.kind === 9; - if (node.parent.kind !== 248 && !inAmbientExternalModule) { - error(moduleName, node.kind === 228 ? + var inAmbientExternalModule = node.parent.kind === 221 && node.parent.parent.name.kind === 9; + if (node.parent.kind !== 250 && !inAmbientExternalModule) { + error(moduleName, node.kind === 230 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -21340,7 +21909,7 @@ var ts; (symbol.flags & 793056 ? 793056 : 0) | (symbol.flags & 1536 ? 1536 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 230 ? + var message = node.kind === 232 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -21366,7 +21935,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224) { + if (importClause.namedBindings.kind === 226) { checkImportBinding(importClause.namedBindings); } else { @@ -21417,8 +21986,8 @@ var ts; if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause) { ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 219 && node.parent.parent.name.kind === 9; - if (node.parent.kind !== 248 && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 221 && node.parent.parent.name.kind === 9; + if (node.parent.kind !== 250 && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -21431,7 +22000,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 248 && node.parent.kind !== 219 && node.parent.kind !== 218) { + if (node.parent.kind !== 250 && node.parent.kind !== 221 && node.parent.kind !== 220) { return grammarErrorOnFirstToken(node, errorMessage); } } @@ -21445,8 +22014,8 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { return; } - var container = node.parent.kind === 248 ? node.parent : node.parent.parent; - if (container.kind === 218 && container.name.kind === 69) { + var container = node.parent.kind === 250 ? node.parent : node.parent.parent; + if (container.kind === 220 && container.name.kind === 69) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } @@ -21469,15 +22038,6 @@ var ts; } } } - function getModuleStatements(node) { - if (node.kind === 248) { - return node.statements; - } - if (node.kind === 218 && node.body.kind === 219) { - return node.body.statements; - } - return emptyArray; - } function hasExportedMembers(moduleSymbol) { for (var id in moduleSymbol.exports) { if (id !== "export=") { @@ -21495,13 +22055,41 @@ var ts; var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } + var exports = getExportsOfModule(moduleSymbol); + for (var id in exports) { + if (id === "__export") { + continue; + } + var _a = exports[id], declarations = _a.declarations, flags = _a.flags; + if (!(flags & (1536 | 64 | 384)) && (flags & 524288 ? declarations.length - 1 : declarations.length) > 1) { + var exportedDeclarations = ts.filter(declarations, isNotOverload); + if (exportedDeclarations.length > 1) { + for (var _i = 0, exportedDeclarations_1 = exportedDeclarations; _i < exportedDeclarations_1.length; _i++) { + var declaration = exportedDeclarations_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); + } + } + } + } links.exportsChecked = true; } + function isNotOverload(declaration) { + return declaration.kind !== 215 || !!declaration.body; + } } function checkTypePredicate(node) { - if (!isInLegalTypePredicatePosition(node)) { + var parameterName = node.parameterName; + if (parameterName.kind === 69 && !isInLegalParameterTypePredicatePosition(node)) { error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); } + else if (parameterName.kind === 161) { + if (!isInLegalThisTypePredicatePosition(node)) { + error(node, ts.Diagnostics.A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_return_type_positions_for_functions_and_methods); + } + else { + getTypeFromThisTypeNode(parameterName); + } + } } function checkSourceElement(node) { if (!node) { @@ -21510,10 +22098,10 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { - case 218: - case 214: + case 220: + case 216: + case 217: case 215: - case 213: cancellationToken.throwIfCancellationRequested(); } } @@ -21557,170 +22145,97 @@ var ts; return checkUnionOrIntersectionType(node); case 160: return checkSourceElement(node.type); - case 213: - return checkFunctionDeclaration(node); - case 192: - case 219: - return checkBlock(node); - case 193: - return checkVariableStatement(node); - case 195: - return checkExpressionStatement(node); - case 196: - return checkIfStatement(node); - case 197: - return checkDoStatement(node); - case 198: - return checkWhileStatement(node); - case 199: - return checkForStatement(node); - case 200: - return checkForInStatement(node); - case 201: - return checkForOfStatement(node); - case 202: - case 203: - return checkBreakOrContinueStatement(node); - case 204: - return checkReturnStatement(node); - case 205: - return checkWithStatement(node); - case 206: - return checkSwitchStatement(node); - case 207: - return checkLabeledStatement(node); - case 208: - return checkThrowStatement(node); - case 209: - return checkTryStatement(node); - case 211: - return checkVariableDeclaration(node); - case 163: - return checkBindingElement(node); - case 214: - return checkClassDeclaration(node); case 215: - return checkInterfaceDeclaration(node); - case 216: - return checkTypeAliasDeclaration(node); - case 217: - return checkEnumDeclaration(node); - case 218: - return checkModuleDeclaration(node); - case 222: - return checkImportDeclaration(node); - case 221: - return checkImportEqualsDeclaration(node); - case 228: - return checkExportDeclaration(node); - case 227: - return checkExportAssignment(node); + return checkFunctionDeclaration(node); case 194: - checkGrammarStatementInAmbientContext(node); - return; + case 221: + return checkBlock(node); + case 195: + return checkVariableStatement(node); + case 197: + return checkExpressionStatement(node); + case 198: + return checkIfStatement(node); + case 199: + return checkDoStatement(node); + case 200: + return checkWhileStatement(node); + case 201: + return checkForStatement(node); + case 202: + return checkForInStatement(node); + case 203: + return checkForOfStatement(node); + case 204: + case 205: + return checkBreakOrContinueStatement(node); + case 206: + return checkReturnStatement(node); + case 207: + return checkWithStatement(node); + case 208: + return checkSwitchStatement(node); + case 209: + return checkLabeledStatement(node); case 210: + return checkThrowStatement(node); + case 211: + return checkTryStatement(node); + case 213: + return checkVariableDeclaration(node); + case 165: + return checkBindingElement(node); + case 216: + return checkClassDeclaration(node); + case 217: + return checkInterfaceDeclaration(node); + case 218: + return checkTypeAliasDeclaration(node); + case 219: + return checkEnumDeclaration(node); + case 220: + return checkModuleDeclaration(node); + case 224: + return checkImportDeclaration(node); + case 223: + return checkImportEqualsDeclaration(node); + case 230: + return checkExportDeclaration(node); + case 229: + return checkExportAssignment(node); + case 196: checkGrammarStatementInAmbientContext(node); return; - case 231: + case 212: + checkGrammarStatementInAmbientContext(node); + return; + case 233: return checkMissingDeclaration(node); } } - function checkFunctionAndClassExpressionBodies(node) { - switch (node.kind) { - case 173: - case 174: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - checkFunctionExpressionOrObjectLiteralMethodBody(node); - break; - case 186: - ts.forEach(node.members, checkSourceElement); - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; - case 143: - case 142: - ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - if (ts.isObjectLiteralMethod(node)) { - checkFunctionExpressionOrObjectLiteralMethodBody(node); - } - break; - case 144: - case 145: - case 146: - case 213: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - break; - case 205: - checkFunctionAndClassExpressionBodies(node.expression); - break; - case 139: - case 138: - case 141: - case 140: - case 161: - case 162: - case 163: - case 164: - case 165: - case 245: - case 166: - case 167: - case 168: - case 169: - case 170: - case 183: - case 190: - case 171: - case 189: - case 172: - case 176: - case 177: - case 178: - case 175: - case 179: - case 180: - case 181: - case 182: - case 185: - case 184: - case 192: - case 219: - case 193: - case 195: - case 196: - case 197: - case 198: - case 199: - case 200: - case 201: - case 202: - case 203: - case 204: - case 206: - case 220: - case 241: - case 242: - case 207: - case 208: - case 209: - case 244: - case 211: - case 212: - case 214: - case 243: - case 188: - case 217: - case 247: - case 227: - case 248: - case 240: - case 233: - case 234: - case 238: - case 239: - case 235: - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 175: + case 176: + case 143: + case 142: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 145: + case 146: + checkAccessorDeferred(node); + break; + case 188: + checkClassExpressionDeferred(node); + break; + } } } function checkSourceFile(node) { @@ -21740,9 +22255,12 @@ var ts; emitExtends = false; emitDecorate = false; emitParam = false; + emitAwaiter = false; potentialThisCollisions.length = 0; + deferredNodes = []; ts.forEach(node.statements, checkSourceElement); - checkFunctionAndClassExpressionBodies(node); + checkDeferredNodes(); + deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -21798,7 +22316,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 205 && node.parent.statement === node) { + if (node.parent.kind === 207 && node.parent.statement === node) { return true; } node = node.parent; @@ -21820,28 +22338,28 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 248: + case 250: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 218: + case 220: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); break; - case 217: + case 219: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 186: + case 188: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 214: - case 215: + case 216: + case 217: if (!(memberFlags & 64)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; - case 173: + case 175: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -21881,10 +22399,10 @@ var ts; function isTypeDeclaration(node) { switch (node.kind) { case 137: - case 214: - case 215: case 216: case 217: + case 218: + case 219: return true; } } @@ -21897,19 +22415,19 @@ var ts; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 166) { + while (node.parent && node.parent.kind === 168) { node = node.parent; } - return node.parent && node.parent.kind === 188; + return node.parent && node.parent.kind === 190; } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { while (nodeOnRightSide.parent.kind === 135) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 221) { + if (nodeOnRightSide.parent.kind === 223) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 227) { + if (nodeOnRightSide.parent.kind === 229) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -21921,10 +22439,10 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 227) { + if (entityName.parent.kind === 229) { return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); } - if (entityName.kind !== 166) { + if (entityName.kind !== 168) { if (isInRightSideOfImportOrExportAssignment(entityName)) { return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); } @@ -21934,7 +22452,7 @@ var ts; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; - if (entityName.parent.kind === 188) { + if (entityName.parent.kind === 190) { meaning = 793056; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; @@ -21946,9 +22464,9 @@ var ts; meaning |= 8388608; return resolveEntityName(entityName, meaning); } - else if ((entityName.parent.kind === 235) || - (entityName.parent.kind === 234) || - (entityName.parent.kind === 237)) { + else if ((entityName.parent.kind === 237) || + (entityName.parent.kind === 236) || + (entityName.parent.kind === 239)) { return getJsxElementTagSymbol(entityName.parent); } else if (ts.isExpression(entityName)) { @@ -21959,7 +22477,7 @@ var ts; var meaning = 107455 | 8388608; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 166) { + else if (entityName.kind === 168) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); @@ -21979,7 +22497,7 @@ var ts; meaning |= 8388608; return resolveEntityName(entityName, meaning); } - else if (entityName.parent.kind === 238) { + else if (entityName.parent.kind === 240) { return getJsxAttributePropertySymbol(entityName.parent); } if (entityName.parent.kind === 150) { @@ -21996,12 +22514,12 @@ var ts; } if (node.kind === 69) { if (isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 227 + return node.parent.kind === 229 ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } - else if (node.parent.kind === 163 && - node.parent.parent.kind === 161 && + else if (node.parent.kind === 165 && + node.parent.parent.kind === 163 && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -22012,13 +22530,15 @@ var ts; } switch (node.kind) { case 69: - case 166: + case 168: case 135: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 97: case 95: var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; + case 161: + return getTypeFromTypeNode(node).symbol; case 121: var constructorDeclaration = node.parent; if (constructorDeclaration && constructorDeclaration.kind === 144) { @@ -22028,12 +22548,12 @@ var ts; case 9: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 222 || node.parent.kind === 228) && + ((node.parent.kind === 224 || node.parent.kind === 230) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } case 8: - if (node.parent.kind === 167 && node.parent.argumentExpression === node) { + if (node.parent.kind === 169 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -22047,7 +22567,7 @@ var ts; return undefined; } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 246) { + if (location && location.kind === 248) { return resolveEntityName(location.name, 107455); } return undefined; @@ -22138,6 +22658,25 @@ var ts; function isArgumentsLocalBinding(node) { return getReferencedValueSymbol(node) === argumentsSymbol; } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol) { + return true; + } + var hasExportAssignment = getExportAssignmentSymbol(moduleSymbol) !== undefined; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455) + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455); + } + } function getReferencedExportContainer(node) { var symbol = getReferencedValueSymbol(node); if (symbol) { @@ -22150,11 +22689,11 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 248) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 250) { return parentSymbol.valueDeclaration; } for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 218 || n.kind === 217) && getSymbolOfNode(n) === parentSymbol) { + if ((n.kind === 220 || n.kind === 219) && getSymbolOfNode(n) === parentSymbol) { return n; } } @@ -22167,11 +22706,11 @@ var ts; } function isStatementWithLocals(node) { switch (node.kind) { - case 192: - case 220: - case 199: - case 200: + case 194: + case 222: case 201: + case 202: + case 203: return true; } return false; @@ -22197,22 +22736,22 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 221: case 223: - case 224: + case 225: case 226: - case 230: - return isAliasResolvedToValue(getSymbolOfNode(node)); case 228: + case 232: + return isAliasResolvedToValue(getSymbolOfNode(node)); + case 230: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 227: + case 229: return node.expression && node.expression.kind === 69 ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 248 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 250 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -22260,7 +22799,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 247) { + if (node.kind === 249) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -22346,17 +22885,6 @@ var ts; var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } - function instantiateSingleCallFunctionType(functionType, typeArguments) { - if (functionType === unknownType) { - return unknownType; - } - var signature = getSingleCallSignature(functionType); - if (!signature) { - return unknownType; - } - var instantiatedSignature = getSignatureInstantiation(signature, typeArguments); - return getOrCreateTypeFromSignature(instantiatedSignature); - } function createResolver() { return { getReferencedExportContainer: getReferencedExportContainer, @@ -22380,6 +22908,7 @@ var ts; getReferencedValueDeclaration: getReferencedValueDeclaration, getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, isArgumentsLocalBinding: isArgumentsLocalBinding, getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration }; @@ -22390,7 +22919,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 248); + return ts.getDeclarationOfKind(moduleSymbol, 250); } function initializeTypeChecker() { ts.forEach(host.getSourceFiles(), function (file) { @@ -22401,10 +22930,10 @@ var ts; mergeSymbolTable(globals, file.locals); } }); + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); getSymbolLinks(unknownSymbol).type = unknownType; - globals[undefinedSymbol.name] = undefinedSymbol; globalArrayType = getGlobalType("Array", 1); globalObjectType = getGlobalType("Object"); globalFunctionType = getGlobalType("Function"); @@ -22465,7 +22994,12 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + if (node.kind === 143 && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } } else if (node.kind === 145 || node.kind === 146) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); @@ -22485,30 +23019,30 @@ var ts; case 143: case 142: case 149: - case 218: - case 222: - case 221: - case 228: - case 227: + case 220: + case 224: + case 223: + case 230: + case 229: case 138: break; - case 213: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && - node.parent.kind !== 219 && node.parent.kind !== 248) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 214: case 215: - case 193: - case 216: - if (node.modifiers && node.parent.kind !== 219 && node.parent.kind !== 248) { + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && + node.parent.kind !== 221 && node.parent.kind !== 250) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; + case 216: case 217: + case 195: + case 218: + if (node.modifiers && node.parent.kind !== 221 && node.parent.kind !== 250) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 219: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74) && - node.parent.kind !== 219 && node.parent.kind !== 248) { + node.parent.kind !== 221 && node.parent.kind !== 250) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; @@ -22523,6 +23057,11 @@ var ts; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; switch (modifier.kind) { + case 74: + if (node.kind !== 219 && node.parent.kind === 216) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74)); + } + break; case 112: case 111: case 110: @@ -22547,7 +23086,7 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 219 || node.parent.kind === 248) { + else if (node.parent.kind === 221 || node.parent.kind === 250) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } else if (flags & 128) { @@ -22567,7 +23106,7 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 219 || node.parent.kind === 248) { + else if (node.parent.kind === 221 || node.parent.kind === 250) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); } else if (node.kind === 138) { @@ -22592,7 +23131,7 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 216) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } else if (node.kind === 138) { @@ -22607,13 +23146,13 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 216) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } else if (node.kind === 138) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 221) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 4; @@ -22623,11 +23162,11 @@ var ts; if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 214) { + if (node.kind !== 216) { if (node.kind !== 143) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); } - if (!(node.parent.kind === 214 && node.parent.flags & 128)) { + if (!(node.parent.kind === 216 && node.parent.flags & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 64) { @@ -22672,7 +23211,7 @@ var ts; } return; } - else if ((node.kind === 222 || node.kind === 221) && flags & 4) { + else if ((node.kind === 224 || node.kind === 223) && flags & 4) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 138 && (flags & 56) && ts.isBindingPattern(node.name)) { @@ -22688,9 +23227,9 @@ var ts; } switch (node.kind) { case 143: - case 213: - case 173: - case 174: + case 215: + case 175: + case 176: if (!node.asteriskToken) { return false; } @@ -22755,7 +23294,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 174) { + if (node.kind === 176) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -22822,7 +23361,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { var arg = args_1[_i]; - if (arg.kind === 187) { + if (arg.kind === 189) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -22897,14 +23436,14 @@ var ts; return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 181 && computedPropertyName.expression.operatorToken.kind === 24) { + if (computedPropertyName.expression.kind === 183 && computedPropertyName.expression.operatorToken.kind === 24) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 213 || - node.kind === 173 || + ts.Debug.assert(node.kind === 215 || + node.kind === 175 || node.kind === 143); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); @@ -22928,19 +23467,23 @@ var ts; var GetAccessor = 2; var SetAccesor = 4; var GetOrSetAccessor = GetAccessor | SetAccesor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; + var _loop_1 = function(prop) { var name_16 = prop.name; - if (prop.kind === 187 || + if (prop.kind === 189 || name_16.kind === 136) { checkGrammarComputedPropertyName(name_16); - continue; + return "continue"; } - if (prop.kind === 246 && !inDestructuring && prop.objectAssignmentInitializer) { - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + if (prop.kind === 248 && !inDestructuring && prop.objectAssignmentInitializer) { + return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; } + ts.forEach(prop.modifiers, function (mod) { + if (mod.kind !== 118 || prop.kind !== 143) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + }); var currentKind = void 0; - if (prop.kind === 245 || prop.kind === 246) { + if (prop.kind === 247 || prop.kind === 248) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name_16.kind === 8) { checkGrammarNumericLiteral(name_16); @@ -22965,27 +23508,33 @@ var ts; else { var existingKind = seen[name_16.text]; if (currentKind === Property && existingKind === Property) { - continue; + return "continue"; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[name_16.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return { value: grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return { value: grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } + }; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var state_1 = _loop_1(prop); + if (typeof state_1 === "object") return state_1.value + if (state_1 === "continue") continue; } } function checkGrammarJsxElement(node) { var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 239) { + if (attr.kind === 241) { continue; } var jsxAttr = attr; @@ -22997,7 +23546,7 @@ var ts; return grammarErrorOnNode(name_17, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 240 && !initializer.expression) { + if (initializer && initializer.kind === 242 && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -23006,24 +23555,28 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 212) { + if (forInOrOfStatement.initializer.kind === 214) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { - if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 200 + var declarations = variableList.declarations; + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 202 ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } - var firstDeclaration = variableList.declarations[0]; + var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 200 + var diagnostic = forInOrOfStatement.kind === 202 ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 200 + var diagnostic = forInOrOfStatement.kind === 202 ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -23084,7 +23637,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 165) { + if (node.parent.kind === 167) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -23103,7 +23656,7 @@ var ts; return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); } } - else if (node.parent.kind === 215) { + else if (node.parent.kind === 217) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); } else if (node.parent.kind === 155) { @@ -23117,9 +23670,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 207: + case 209: if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 202 + var isMisplacedContinueLabel = node.kind === 204 && !ts.isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -23127,8 +23680,8 @@ var ts; return false; } break; - case 206: - if (node.kind === 203 && !node.label) { + case 208: + if (node.kind === 205 && !node.label) { return false; } break; @@ -23141,13 +23694,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 203 + var message = node.kind === 205 ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 203 + var message = node.kind === 205 ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -23159,7 +23712,7 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } - if (node.name.kind === 162 || node.name.kind === 161) { + if (node.name.kind === 164 || node.name.kind === 163) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -23168,7 +23721,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 200 && node.parent.parent.kind !== 201) { + if (node.parent.parent.kind !== 202 && node.parent.parent.kind !== 203) { if (ts.isInAmbientContext(node)) { if (node.initializer) { var equalsTokenLength = "=".length; @@ -23184,12 +23737,12 @@ var ts; } } } - var checkLetConstNames = languageVersion >= 2 && (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 69) { - if (name.text === "let") { + if (name.originalKeywordKind === 108) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -23197,7 +23750,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 187) { + if (element.kind !== 189) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -23214,15 +23767,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 196: - case 197: case 198: - case 205: case 199: case 200: - case 201: - return false; case 207: + case 201: + case 202: + case 203: + return false; + case 209: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -23237,18 +23790,6 @@ var ts; } } } - function isIntegerLiteral(expression) { - if (expression.kind === 179) { - var unaryExpression = expression; - if (unaryExpression.operator === 35 || unaryExpression.operator === 36) { - expression = unaryExpression.operand; - } - } - if (expression.kind === 8) { - return /^[0-9]+([eE]\+?[0-9]+)?$/.test(expression.text); - } - return false; - } function hasParseDiagnostics(sourceFile) { return sourceFile.parseDiagnostics.length > 0; } @@ -23273,10 +23814,6 @@ var ts; return true; } } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 && - (node.text === "eval" || node.text === "arguments"); - } function checkGrammarConstructorTypeParameters(node) { if (node.typeParameters) { return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); @@ -23294,27 +23831,33 @@ var ts; return true; } } - else if (node.parent.kind === 215) { + else if (node.parent.kind === 217) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } } else if (node.parent.kind === 155) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } } if (ts.isInAmbientContext(node) && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 215 || - node.kind === 216 || - node.kind === 222 || - node.kind === 221 || - node.kind === 228 || - node.kind === 227 || + if (node.kind === 217 || + node.kind === 218 || + node.kind === 224 || + node.kind === 223 || + node.kind === 230 || + node.kind === 229 || (node.flags & 4) || (node.flags & (2 | 512))) { return false; @@ -23324,7 +23867,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 193) { + if (ts.isDeclaration(decl) || decl.kind === 195) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -23343,7 +23886,7 @@ var ts; if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } - if (node.parent.kind === 192 || node.parent.kind === 219 || node.parent.kind === 248) { + if (node.parent.kind === 194 || node.parent.kind === 221 || node.parent.kind === 250) { var links_1 = getNodeLinks(node.parent); if (!links_1.hasReportedStatementInAmbientContext) { return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -23366,19 +23909,248 @@ var ts; return true; } } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); var ts; +(function (ts) { + var nullSourceMapWriter; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitStart: function (range) { }, + emitEnd: function (range) { }, + emitPos: function (pos) { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; }, + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + var currentSourceFile; + var sourceMapDir; + var sourceMapSourceIndex; + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan; + var lastEncodedNameIndex; + var sourceMapData; + return { + getSourceMapData: function () { return sourceMapData; }, + setSourceFile: setSourceFile, + emitPos: emitPos, + emitStart: emitStart, + emitEnd: emitEnd, + getText: getText, + getSourceMappingURL: getSourceMappingURL, + initialize: initialize, + reset: reset + }; + function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (sourceMapData) { + reset(); + } + currentSourceFile = undefined; + sourceMapSourceIndex = -1; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + lastEncodedNameIndex = 0; + sourceMapData = { + sourceMapFilePath: sourceMapFilePath, + jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, + sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, + sourceMapDecodedMappings: [] + }; + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (!isBundledEmit) { + ts.Debug.assert(sourceFiles.length === 1); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); + } + } + function reset() { + currentSourceFile = undefined; + sourceMapDir = undefined; + sourceMapSourceIndex = undefined; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = undefined; + lastEncodedNameIndex = undefined; + sourceMapData = undefined; + } + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + } + function emitPos(pos) { + if (pos === -1) { + return; + } + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + sourceLinePos.line++; + sourceLinePos.character++; + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + if (!lastRecordedSourceMapSpan || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || + (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && + (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || + (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + sourceIndex: sourceMapSourceIndex + }; + } + else { + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + } + function emitStart(range) { + var rangeHasDecorators = !!range.decorators; + emitPos(range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1); + } + function emitEnd(range) { + emitPos(range.end); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + if (sourceMapSourceIndex === -1) { + sourceMapSourceIndex = sourceMapData.sourceMapSources.length; + sourceMapData.sourceMapSources.push(source); + sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + if (compilerOptions.inlineSources) { + sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + } + } + } + function getText() { + encodeLastRecordedSourceMapSpan(); + return ts.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent + }); + } + function getSourceMappingURL() { + if (compilerOptions.inlineSourceMap) { + var base64SourceMapText = ts.convertToBase64(getText()); + return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; + } + else { + return sourceMapData.jsSourceMappingURL; + } + } + } + ts.createSourceMapWriter = createSourceMapWriter; + var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function base64FormatEncode(inValue) { + if (inValue < 64) { + return base64Chars.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + function base64VLQFormatEncode(inValue) { + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } +})(ts || (ts = {})); +var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var diagnostics = []; - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); - emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); - return diagnostics; + var declarationDiagnostics = ts.createDiagnosticCollection(); + ts.forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); + return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName); + function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { + var declarationFilePath = _a.declarationFilePath; + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -23396,93 +24168,67 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare = !root; + var noDeclare; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencePathsOutput = ""; - if (root) { + var emittedReferencedFiles = []; + var addedGlobalFileReference = false; + var allSourcesModuleElementDeclarationEmitInfo = []; + ts.forEach(sourceFiles, function (sourceFile) { + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } if (!compilerOptions.noResolve) { - var addedGlobalFileReference = false; - ts.forEach(root.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); - if (referencedFile && ((referencedFile.flags & 4096) || - ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || - !addedGlobalFileReference)) { - writeReferencePath(referencedFile); - if (!ts.isExternalModuleOrDeclarationFile(referencedFile)) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } + emittedReferencedFiles.push(referencedFile); } }); } - emitSourceFile(root); + if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { + noDeclare = false; + emitSourceFile(sourceFile); + } + else if (ts.isExternalModule(sourceFile)) { + noDeclare = true; + write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); + writeLine(); + increaseIndent(); + emitSourceFile(sourceFile); + decreaseIndent(); + write("}"); + writeLine(); + } if (moduleElementDeclarationEmitInfo.length) { var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222); + if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { + ts.Debug.assert(aliasEmitInfo.node.kind === 224); createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0); + ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + increaseIndent(); + } writeImportDeclaration(aliasEmitInfo.node); aliasEmitInfo.asynchronousOutput = writer.getText(); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + decreaseIndent(); + } } }); setWriter(oldWriter); + allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); + moduleElementDeclarationEmitInfo = []; } - } - else { - var emittedReferencedFiles = []; - var prevModuleElementDeclarationEmitInfo = []; - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!ts.isDeclarationFile(sourceFile)) { - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - if (referencedFile && (ts.isDeclarationFile(referencedFile) && - !ts.contains(emittedReferencedFiles, referencedFile))) { - writeReferencePath(referencedFile); - emittedReferencedFiles.push(referencedFile); - } - }); - } - } - if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) { - noDeclare = false; - emitSourceFile(sourceFile); - } - else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; - write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - write("}"); - writeLine(); - if (moduleElementDeclarationEmitInfo.length) { - var oldWriter = writer; - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222); - createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 1); - increaseIndent(); - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - decreaseIndent(); - } - }); - setWriter(oldWriter); - } - prevModuleElementDeclarationEmitInfo = prevModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - }); - moduleElementDeclarationEmitInfo = moduleElementDeclarationEmitInfo.concat(prevModuleElementDeclarationEmitInfo); - } + }); return { reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: moduleElementDeclarationEmitInfo, + moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), referencePathsOutput: referencePathsOutput }; @@ -23525,10 +24271,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 211) { + if (declaration.kind === 213) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 225 || declaration.kind === 226 || declaration.kind === 223) { + else if (declaration.kind === 227 || declaration.kind === 228 || declaration.kind === 225) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -23539,7 +24285,7 @@ var ts; moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 222) { + if (moduleElementEmitInfo.node.kind === 224) { moduleElementEmitInfo.isVisible = true; } else { @@ -23547,12 +24293,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 218) { + if (nodeToCheck.kind === 220) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 218) { + if (nodeToCheck.kind === 220) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -23573,10 +24319,10 @@ var ts; var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); if (errorInfo) { if (errorInfo.typeName) { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); } else { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); } } } @@ -23586,7 +24332,8 @@ var ts; } function reportInaccessibleThisError() { if (errorNameNode) { - diagnostics.push(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { @@ -23654,10 +24401,10 @@ var ts; case 120: case 131: case 103: - case 97: - case 9: + case 161: + case 162: return writeTextOfNode(currentText, type); - case 188: + case 190: return emitExpressionWithTypeArguments(type); case 151: return emitTypeReference(type); @@ -23698,13 +24445,13 @@ var ts; } } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 221 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 223 ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 166); + ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 168); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -23777,7 +24524,8 @@ var ts; } var count = 0; while (true) { - var name_18 = baseName + "_" + (++count); + count++; + var name_18 = baseName + "_" + count; if (!ts.hasProperty(currentIdentifiers, name_18)) { return name_18; } @@ -23820,10 +24568,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 221 || - (node.parent.kind === 248 && isCurrentFileExternalModule)) { + else if (node.kind === 223 || + (node.parent.kind === 250 && isCurrentFileExternalModule)) { var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 250) { asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -23832,7 +24580,7 @@ var ts; }); } else { - if (node.kind === 222) { + if (node.kind === 224) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -23850,37 +24598,37 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 213: - return writeFunctionDeclaration(node); - case 193: - return writeVariableStatement(node); case 215: - return writeInterfaceDeclaration(node); - case 214: - return writeClassDeclaration(node); - case 216: - return writeTypeAliasDeclaration(node); + return writeFunctionDeclaration(node); + case 195: + return writeVariableStatement(node); case 217: - return writeEnumDeclaration(node); + return writeInterfaceDeclaration(node); + case 216: + return writeClassDeclaration(node); case 218: + return writeTypeAliasDeclaration(node); + case 219: + return writeEnumDeclaration(node); + case 220: return writeModuleDeclaration(node); - case 221: + case 223: return writeImportEqualsDeclaration(node); - case 222: + case 224: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); } } function emitModuleElementDeclarationFlags(node) { - if (node.parent.kind === 248) { + if (node.parent.kind === 250) { if (node.flags & 2) { write("export "); } if (node.flags & 512) { write("default "); } - else if (node.kind !== 215 && !noDeclare) { + else if (node.kind !== 217 && !noDeclare) { write("declare "); } } @@ -23913,7 +24661,7 @@ var ts; } else { write("require("); - writeTextOfNode(currentText, ts.getExternalModuleImportEqualsDeclarationExpression(node)); + emitExternalModuleSpecifier(node); write(");"); } writer.writeLine(); @@ -23927,7 +24675,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 224) { + if (namedBindings.kind === 226) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -23953,7 +24701,7 @@ var ts; if (currentWriterPos !== writer.getTextPos()) { write(", "); } - if (node.importClause.namedBindings.kind === 224) { + if (node.importClause.namedBindings.kind === 226) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -23965,13 +24713,22 @@ var ts; } write(" from "); } - emitExternalModuleSpecifier(node.moduleSpecifier); + emitExternalModuleSpecifier(node); write(";"); writer.writeLine(); } - function emitExternalModuleSpecifier(moduleSpecifier) { - if (moduleSpecifier.kind === 9 && (!root) && (compilerOptions.out || compilerOptions.outFile)) { - var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, moduleSpecifier.parent); + function emitExternalModuleSpecifier(parent) { + var moduleSpecifier; + if (parent.kind === 223) { + var node = parent; + moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); + } + else { + var node = parent; + moduleSpecifier = node.moduleSpecifier; + } + if (moduleSpecifier.kind === 9 && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { + var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); if (moduleName) { write("\""); write(moduleName); @@ -24006,7 +24763,7 @@ var ts; } if (node.moduleSpecifier) { write(" from "); - emitExternalModuleSpecifier(node.moduleSpecifier); + emitExternalModuleSpecifier(node); } write(";"); writer.writeLine(); @@ -24021,7 +24778,7 @@ var ts; write("module "); } writeTextOfNode(currentText, node.name); - while (node.body.kind !== 219) { + while (node.body.kind !== 221) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -24114,10 +24871,10 @@ var ts; function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; switch (node.parent.kind) { - case 214: + case 216: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 215: + case 217: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; case 148: @@ -24131,14 +24888,14 @@ var ts; if (node.parent.flags & 64) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 214) { + else if (node.parent.parent.kind === 216) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 213: + case 215: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -24171,7 +24928,7 @@ var ts; } function getHeritageClauseVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; - if (node.parent.parent.kind === 214) { + if (node.parent.parent.kind === 216) { diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; @@ -24251,7 +25008,7 @@ var ts; writeLine(); } function emitVariableDeclaration(node) { - if (node.kind !== 211 || resolver.isDeclarationVisible(node)) { + if (node.kind !== 213 || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } @@ -24269,7 +25026,7 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 211) { + if (node.kind === 213) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24284,7 +25041,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 216) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24310,7 +25067,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187) { + if (element.kind !== 189) { elements.push(element); } } @@ -24444,13 +25201,13 @@ var ts; } if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 213) { + if (node.kind === 215) { emitModuleElementDeclarationFlags(node); } else if (node.kind === 143) { emitClassMemberDeclarationFlags(node); } - if (node.kind === 213) { + if (node.kind === 215) { write("function "); writeTextOfNode(currentText, node.name); } @@ -24471,6 +25228,8 @@ var ts; emitSignatureDeclaration(node); } function emitSignatureDeclaration(node) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; if (node.kind === 148 || node.kind === 153) { write("new "); } @@ -24481,8 +25240,6 @@ var ts; else { write("("); } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitCommaList(node.parameters, emitParameterDeclaration); if (node.kind === 149) { write("]"); @@ -24532,7 +25289,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 216) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -24545,7 +25302,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 213: + case 215: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -24618,7 +25375,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 214) { + else if (node.parent.parent.kind === 216) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24630,7 +25387,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 213: + case 215: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24641,12 +25398,12 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 161) { + if (bindingPattern.kind === 163) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 162) { + else if (bindingPattern.kind === 164) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -24657,18 +25414,10 @@ var ts; } } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.kind === 187) { + if (bindingElement.kind === 189) { write(" "); } - else if (bindingElement.kind === 163) { + else if (bindingElement.kind === 165) { if (bindingElement.propertyName) { writeTextOfNode(currentText, bindingElement.propertyName); write(": "); @@ -24690,19 +25439,19 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 213: - case 218: - case 221: case 215: - case 214: - case 216: + case 220: + case 223: case 217: + case 216: + case 218: + case 219: return emitModuleElement(node, isModuleElementVisible(node)); - case 193: + case 195: return emitModuleElement(node, isVariableStatementVisible(node)); - case 222: + case 224: return emitModuleElement(node, !node.importClause); - case 228: + case 230: return emitExportDeclaration(node); case 144: case 143: @@ -24718,31 +25467,47 @@ var ts; case 141: case 140: return emitPropertyDeclaration(node); - case 247: + case 249: return emitEnumMemberDeclaration(node); - case 227: + case 229: return emitExportAssignment(node); - case 248: + case 250: return emitSourceFile(node); } } - function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 4096 - ? referencedFile.fileName - : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) - ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") - : ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); - referencePathsOutput += "/// " + newLine; + function writeReferencePath(referencedFile, addBundledFileReference) { + var declFileName; + var addedBundledEmitReference = false; + if (ts.isDeclarationFile(referencedFile)) { + declFileName = referencedFile.fileName; + } + else { + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + } + if (declFileName) { + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); + referencePathsOutput += "/// " + newLine; + } + return addedBundledEmitReference; + function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + if (isBundledEmit && !addBundledFileReference) { + return; + } + ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); + declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; + addedBundledEmitReference = isBundledEmit; + } } } - function writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); - if (!emitDeclarationResult.reportedDeclarationError) { + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; + if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); + ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM); } + return emitSkipped; function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { var appliedSyncOutputPos = 0; var declarationOutput = ""; @@ -24761,10 +25526,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); - } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; function getResolvedExternalModuleName(host, file) { return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); } @@ -25039,41 +25800,17 @@ var ts; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\n return new Promise(function (resolve, reject) {\n generator = generator.call(thisArg, _arguments);\n function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\n function onfulfill(value) { try { step(\"next\", value); } catch (e) { reject(e); } }\n function onreject(value) { try { step(\"throw\", value); } catch (e) { reject(e); } }\n function step(verb, value) {\n var result = generator[verb](value);\n result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\n }\n step(\"next\", void 0);\n });\n};"; var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || 0; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 ? 5 : 0; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; - var diagnostics = []; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emitSkipped = false; var newLine = host.getNewLine(); - var jsxDesugaring = host.getCompilerOptions().jsx !== 1; - var shouldEmitJsx = function (s) { return (s.languageVariant === 1 && !jsxDesugaring); }; - var outFile = compilerOptions.outFile || compilerOptions.out; var emitJavaScript = createFileEmitter(); - if (targetSourceFile === undefined) { - if (outFile) { - emitFile(outFile); - } - else { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - } - } - else { - if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!ts.isDeclarationFile(targetSourceFile) && outFile) { - emitFile(outFile); - } - } - diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { - emitSkipped: false, - diagnostics: diagnostics, + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), sourceMaps: sourceMapDataList }; function isUniqueLocalName(name, container) { @@ -25120,6 +25857,8 @@ var ts; function createFileEmitter() { var writer = ts.createTextWriter(newLine); var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); + var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; var currentSourceFile; var currentText; var currentLineMap; @@ -25136,24 +25875,16 @@ var ts; var decorateEmitted; var paramEmitted; var awaiterEmitted; - var tempFlags; + var tempFlags = 0; var tempVariables; var tempParameters; var externalImports; var exportSpecifiers; var exportEquals; - var hasExportStars; - var writeEmittedFiles = writeJavaScriptFile; + var hasExportStarsToExportValues; var detachedCommentsInfo; - var writeComment = ts.writeCommentRange; - var emit = emitNodeWithCommentsAndWithoutSourcemap; - var emitStart = function (node) { }; - var emitEnd = function (node) { }; - var emitToken = emitTokenText; - var scopeEmitStart = function (scopeDeclaration, scopeName) { }; - var scopeEmitEnd = function () { }; var sourceMapData; - var root; + var isOwnFileEmit; var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var moduleEmitDelegates = (_a = {}, _a[5] = emitES6Module, @@ -25172,14 +25903,29 @@ var ts; _b ); return doEmit; - function doEmit(jsFilePath, rootFile) { + function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + generatedNameSet = {}; + nodeToGeneratedName = []; + isOwnFileEmit = !isBundledEmit; + if (isBundledEmit && modulekind) { + ts.forEach(sourceFiles, emitEmitHelpers); + } + ts.forEach(sourceFiles, emitSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# sourceMappingURL=" + sourceMappingURL); + } + writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM); + sourceMap.reset(); writer.reset(); currentSourceFile = undefined; currentText = undefined; currentLineMap = undefined; exportFunctionForFile = undefined; - generatedNameSet = {}; - nodeToGeneratedName = []; + generatedNameSet = undefined; + nodeToGeneratedName = undefined; computedPropertyNamesToGeneratedNames = undefined; convertedLoopState = undefined; extendsEmitted = false; @@ -25192,31 +25938,12 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = undefined; + hasExportStarsToExportValues = undefined; detachedCommentsInfo = undefined; sourceMapData = undefined; isEs6Module = false; renamedDependencies = undefined; isCurrentFileExternalModule = false; - root = rootFile; - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - initializeEmitterWithSourceMaps(jsFilePath, root); - } - if (root) { - emitSourceFile(root); - } - else { - if (modulekind) { - ts.forEach(host.getSourceFiles(), emitEmitHelpers); - } - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if ((!isExternalModuleOrDeclarationFile(sourceFile)) || (modulekind && ts.isExternalModule(sourceFile))) { - emitSourceFile(sourceFile); - } - }); - } - writeLine(); - writeEmittedFiles(writer.getText(), jsFilePath, compilerOptions.emitBOM); } function emitSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -25227,7 +25954,8 @@ var ts; renamedDependencies = sourceFile.renamedDependencies; currentFileIdentifiers = sourceFile.identifiers; isCurrentFileExternalModule = ts.isExternalModule(sourceFile); - emit(sourceFile); + setSourceFile(sourceFile); + emitNodeWithCommentsAndWithoutSourcemap(sourceFile); } function isUniqueName(name) { return !resolver.hasGlobalName(name) && @@ -25286,17 +26014,17 @@ var ts; switch (node.kind) { case 69: return makeUniqueName(node.text); - case 218: - case 217: + case 220: + case 219: return generateNameForModuleOrEnum(node); - case 222: - case 228: + case 224: + case 230: return generateNameForImportOrExportDeclaration(node); - case 213: - case 214: - case 227: + case 215: + case 216: + case 229: return generateNameForExportDefault(); - case 186: + case 188: return generateNameForClassExpression(); } } @@ -25304,289 +26032,14 @@ var ts; var id = ts.getNodeId(node); return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); } - function initializeEmitterWithSourceMaps(jsFilePath, root) { - var sourceMapDir; - var sourceMapSourceIndex = -1; - var sourceMapNameIndexMap = {}; - var sourceMapNameIndices = []; - function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; + function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark) { + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false); } - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - var lastEncodedNameIndex = 0; - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - function base64VLQFormatEncode(inValue) { - function base64FormatEncode(inValue) { - if (inValue < 64) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - var encodedStr = ""; - do { - var currentDigit = inValue & 31; - inValue = inValue >> 5; - if (inValue > 0) { - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; - } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); } - function recordSourceMapSpan(pos) { - var sourceLinePos = ts.computeLineAndCharacterOfPosition(currentLineMap, pos); - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); - if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine !== emittedLine || - lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || - (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && - (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || - (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - nameIndex: getSourceMapNameIndex(), - sourceIndex: sourceMapSourceIndex - }; - } - else { - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - } - function recordEmitNodeStartSpan(node) { - recordSourceMapSpan(ts.skipTrivia(currentText, node.pos)); - } - function recordEmitNodeEndSpan(node) { - recordSourceMapSpan(node.end); - } - function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentText, startPos); - recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); - recordSourceMapSpan(tokenEndPos); - return tokenEndPos; - } - function recordNewSourceFileStart(node) { - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true)); - sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; - sourceMapData.inputSourceFileNames.push(node.fileName); - if (compilerOptions.inlineSources) { - if (!sourceMapData.sourceMapSourcesContent) { - sourceMapData.sourceMapSourcesContent = []; - } - sourceMapData.sourceMapSourcesContent.push(node.text); - } - } - function recordScopeNameOfNode(node, scopeName) { - function recordScopeNameIndex(scopeNameIndex) { - sourceMapNameIndices.push(scopeNameIndex); - } - function recordScopeNameStart(scopeName) { - var scopeNameIndex = -1; - if (scopeName) { - var parentIndex = getSourceMapNameIndex(); - if (parentIndex !== -1) { - var name_21 = node.name; - if (!name_21 || name_21.kind !== 136) { - scopeName = "." + scopeName; - } - scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; - } - scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); - if (scopeNameIndex === undefined) { - scopeNameIndex = sourceMapData.sourceMapNames.length; - sourceMapData.sourceMapNames.push(scopeName); - sourceMapNameIndexMap[scopeName] = scopeNameIndex; - } - } - recordScopeNameIndex(scopeNameIndex); - } - if (scopeName) { - recordScopeNameStart(scopeName); - } - else if (node.kind === 213 || - node.kind === 173 || - node.kind === 143 || - node.kind === 142 || - node.kind === 145 || - node.kind === 146 || - node.kind === 218 || - node.kind === 214 || - node.kind === 217) { - if (node.name) { - var name_22 = node.name; - scopeName = name_22.kind === 136 - ? ts.getTextOfNode(name_22) - : node.name.text; - } - recordScopeNameStart(scopeName); - } - else { - recordScopeNameIndex(getSourceMapNameIndex()); - } - } - function recordScopeNameEnd() { - sourceMapNameIndices.pop(); - } - ; - function writeCommentRangeWithMap(currentText, currentLineMap, writer, comment, newLine) { - recordSourceMapSpan(comment.pos); - ts.writeCommentRange(currentText, currentLineMap, writer, comment, newLine); - recordSourceMapSpan(comment.end); - } - function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) { - if (typeof JSON !== "undefined") { - var map_1 = { - version: version, - file: file, - sourceRoot: sourceRoot, - sources: sources, - names: names, - mappings: mappings - }; - if (sourcesContent !== undefined) { - map_1.sourcesContent = sourcesContent; - } - return JSON.stringify(map_1); - } - return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\" " + (sourcesContent !== undefined ? ",\"sourcesContent\":[" + serializeStringArray(sourcesContent) + "]" : "") + "}"; - function serializeStringArray(list) { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { - if (i) { - output += ","; - } - output += "\"" + ts.escapeString(list[i]) + "\""; - } - return output; - } - } - function writeJavaScriptAndSourceMapFile(emitOutput, jsFilePath, writeByteOrderMark) { - encodeLastRecordedSourceMapSpan(); - var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent); - sourceMapDataList.push(sourceMapData); - var sourceMapUrl; - if (compilerOptions.inlineSourceMap) { - var base64SourceMapText = ts.convertToBase64(sourceMapText); - sourceMapUrl = "//# sourceMappingURL=data:application/json;base64," + base64SourceMapText; - } - else { - ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, false); - sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL; - } - writeJavaScriptFile(emitOutput + sourceMapUrl, jsFilePath, writeByteOrderMark); - } - var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)); - sourceMapData = { - sourceMapFilePath: jsFilePath + ".map", - jsSourceMappingURL: sourceMapJsFile + ".map", - sourceMapFile: sourceMapJsFile, - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapSourcesContent: undefined, - sourceMapDecodedMappings: [] - }; - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (root) { - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); - } - function emitNodeWithSourceMap(node) { - if (node) { - if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node); - } - if (node.kind !== 248) { - recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node); - recordEmitNodeEndSpan(node); - } - else { - recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node); - } - } - } - function emitNodeWithCommentsAndWithSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - writeEmittedFiles = writeJavaScriptAndSourceMapFile; - emit = emitNodeWithCommentsAndWithSourcemap; - emitStart = recordEmitNodeStartSpan; - emitEnd = recordEmitNodeEndSpan; - emitToken = writeTextWithSpanRecord; - scopeEmitStart = recordScopeNameOfNode; - scopeEmitEnd = recordScopeNameEnd; - writeComment = writeCommentRangeWithMap; - } - function writeJavaScriptFile(emitOutput, jsFilePath, writeByteOrderMark) { - ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark); } function createTempVariable(flags) { var result = ts.createSynthesizedNode(69); @@ -25617,7 +26070,9 @@ var ts; write(";"); } } - function emitTokenText(tokenKind, startPos, emitFn) { + function emitToken(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentText, startPos); + emitPos(tokenStartPos); var tokenString = ts.tokenToString(tokenKind); if (emitFn) { emitFn(); @@ -25625,7 +26080,9 @@ var ts; else { write(tokenString); } - return startPos + tokenString.length; + var tokenEndPos = tokenStartPos + tokenString.length; + emitPos(tokenEndPos); + return tokenEndPos; } function emitOptional(prefix, node) { if (node) { @@ -25642,11 +26099,6 @@ var ts; write(")"); } } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { ts.Debug.assert(nodes.length > 0); increaseIndent(); @@ -25812,10 +26264,10 @@ var ts; emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); write("("); emit(tempVariable); - if (node.template.kind === 183) { + if (node.template.kind === 185) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 181 + var needsParens = templateSpan.expression.kind === 183 && templateSpan.expression.operatorToken.kind === 24; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -25839,7 +26291,7 @@ var ts; } for (var i = 0, n = node.templateSpans.length; i < n; i++) { var templateSpan = node.templateSpans[i]; - var needsParens = templateSpan.expression.kind !== 172 + var needsParens = templateSpan.expression.kind !== 174 && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1; if (i > 0 || headEmitted) { write(" + "); @@ -25859,11 +26311,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 168: - case 169: - return parent.expression === template; case 170: + case 171: + return parent.expression === template; case 172: + case 174: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1; @@ -25871,7 +26323,7 @@ var ts; } function comparePrecedenceToBinaryPlus(expression) { switch (expression.kind) { - case 181: + case 183: switch (expression.operatorToken.kind) { case 37: case 39: @@ -25883,8 +26335,8 @@ var ts; default: return -1; } + case 186: case 184: - case 182: return -1; default: return 1; @@ -25907,13 +26359,13 @@ var ts; } } function emitAttributeName(name) { - if (/[A-Za-z_]+[\w*]/.test(name.text)) { - write("\""); + if (/^[A-Za-z_]\w*$/.test(name.text)) { emit(name); - write("\""); } else { + write("\""); emit(name); + write("\""); } } function emitJsxAttribute(node) { @@ -25928,7 +26380,7 @@ var ts; } function emitJsxElement(openingNode, children) { var syntheticReactRef = ts.createSynthesizedNode(69); - syntheticReactRef.text = "React"; + syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; syntheticReactRef.parent = openingNode; emitLeadingComments(openingNode); emitExpressionIdentifier(syntheticReactRef); @@ -25940,12 +26392,12 @@ var ts; } else { var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 239; })) { + if (ts.forEach(attrs, function (attr) { return attr.kind === 241; })) { emitExpressionIdentifier(syntheticReactRef); write(".__spread("); var haveOpenedObjectLiteral = false; for (var i_1 = 0; i_1 < attrs.length; i_1++) { - if (attrs[i_1].kind === 239) { + if (attrs[i_1].kind === 241) { if (i_1 === 0) { write("{}, "); } @@ -25959,7 +26411,7 @@ var ts; emit(attrs[i_1].expression); } else { - ts.Debug.assert(attrs[i_1].kind === 238); + ts.Debug.assert(attrs[i_1].kind === 240); if (haveOpenedObjectLiteral) { write(", "); } @@ -25990,10 +26442,10 @@ var ts; } if (children) { for (var i = 0; i < children.length; i++) { - if (children[i].kind === 240 && !(children[i].expression)) { + if (children[i].kind === 242 && !(children[i].expression)) { continue; } - if (children[i].kind === 236) { + if (children[i].kind === 238) { var text = getTextToEmit(children[i]); if (text !== undefined) { write(", \""); @@ -26010,11 +26462,11 @@ var ts; write(")"); emitTrailingComments(openingNode); } - if (node.kind === 233) { + if (node.kind === 235) { emitJsxElement(node.openingElement, node.children); } else { - ts.Debug.assert(node.kind === 234); + ts.Debug.assert(node.kind === 236); emitJsxElement(node); } } @@ -26036,11 +26488,11 @@ var ts; if (i > 0) { write(" "); } - if (attribs[i].kind === 239) { + if (attribs[i].kind === 241) { emitJsxSpreadAttribute(attribs[i]); } else { - ts.Debug.assert(attribs[i].kind === 238); + ts.Debug.assert(attribs[i].kind === 240); emitJsxAttribute(attribs[i]); } } @@ -26048,11 +26500,11 @@ var ts; function emitJsxOpeningOrSelfClosingElement(node) { write("<"); emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 234)) { + if (node.attributes.length > 0 || (node.kind === 236)) { write(" "); } emitAttributes(node.attributes); - if (node.kind === 234) { + if (node.kind === 236) { write("/>"); } else { @@ -26071,16 +26523,16 @@ var ts; } emitJsxClosingElement(node.closingElement); } - if (node.kind === 233) { + if (node.kind === 235) { emitJsxElement(node); } else { - ts.Debug.assert(node.kind === 234); + ts.Debug.assert(node.kind === 236); emitJsxOpeningOrSelfClosingElement(node); } } function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 163); + ts.Debug.assert(node.kind !== 165); if (node.kind === 9) { emitLiteral(node); } @@ -26115,59 +26567,60 @@ var ts; function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 164: - case 189: - case 181: - case 168: - case 241: - case 136: - case 182: - case 139: - case 175: - case 197: - case 167: - case 227: - case 195: - case 188: - case 199: - case 200: - case 201: - case 196: - case 234: - case 235: - case 239: - case 240: - case 169: - case 172: - case 180: - case 179: - case 204: - case 246: - case 185: - case 206: - case 170: - case 190: - case 208: - case 171: - case 176: - case 177: - case 198: - case 205: - case 184: - return true; - case 163: - case 247: - case 138: - case 245: - case 141: - case 211: - return parent.initializer === node; case 166: - return parent.expression === node; + case 191: + case 183: + case 170: + case 243: + case 136: + case 184: + case 139: + case 177: + case 199: + case 169: + case 229: + case 197: + case 190: + case 201: + case 202: + case 203: + case 198: + case 239: + case 236: + case 237: + case 241: + case 242: + case 171: case 174: + case 182: + case 181: + case 206: + case 248: + case 187: + case 208: + case 172: + case 192: + case 210: case 173: + case 178: + case 179: + case 200: + case 207: + case 186: + return true; + case 165: + case 249: + case 138: + case 247: + case 141: + case 213: + return parent.initializer === node; + case 168: + return parent.expression === node; + case 176: + case 175: return parent.body === node; - case 221: + case 223: return parent.moduleReference === node; case 135: return parent.left === node; @@ -26181,7 +26634,7 @@ var ts; } var container = resolver.getReferencedExportContainer(node); if (container) { - if (container.kind === 248) { + if (container.kind === 250) { if (modulekind !== 5 && modulekind !== 4) { write("exports."); } @@ -26195,15 +26648,15 @@ var ts; if (modulekind !== 5) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { - if (declaration.kind === 223) { + if (declaration.kind === 225) { write(getGeneratedNameForNode(declaration.parent)); write(languageVersion === 0 ? "[\"default\"]" : ".default"); return; } - else if (declaration.kind === 226) { + else if (declaration.kind === 228) { write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_23 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_23); + var name_21 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_21); if (languageVersion === 0 && identifier === "default") { write("[\"default\"]"); } @@ -26234,10 +26687,10 @@ var ts; if (languageVersion < 2) { var parent_6 = node.parent; switch (parent_6.kind) { - case 163: - case 214: - case 217: - case 211: + case 165: + case 216: + case 219: + case 213: return parent_6.name === node && resolver.isNestedRedeclaration(parent_6); } } @@ -26246,8 +26699,8 @@ var ts; function emitIdentifier(node) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_24 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_24); + var name_22 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_22); return; } } @@ -26271,6 +26724,9 @@ var ts; if (resolver.getNodeCheckFlags(node) & 2) { write("_this"); } + else if (convertedLoopState) { + write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); + } else { write("this"); } @@ -26344,10 +26800,10 @@ var ts; } } function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 181 && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { + if (node.parent.kind === 183 && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { return true; } - else if (node.parent.kind === 182 && node.parent.condition === node) { + else if (node.parent.kind === 184 && node.parent.condition === node) { return true; } return false; @@ -26355,11 +26811,11 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 69: - case 164: case 166: - case 167: case 168: - case 172: + case 169: + case 170: + case 174: return false; } return true; @@ -26376,17 +26832,17 @@ var ts; write(", "); } var e = elements[pos]; - if (e.kind === 185) { + if (e.kind === 187) { e = e.expression; emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 166) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 185) { + while (i < length && elements[i].kind !== 187) { i++; } write("["); @@ -26409,7 +26865,7 @@ var ts; } } function isSpreadElementExpression(node) { - return node.kind === 185; + return node.kind === 187; } function emitArrayLiteral(node) { var elements = node.elements; @@ -26521,10 +26977,10 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 245) { + if (property.kind === 247) { emit(property.initializer); } - else if (property.kind === 246) { + else if (property.kind === 248) { emitExpressionIdentifier(property.name); } else if (property.kind === 143) { @@ -26573,35 +27029,35 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(181, startsOnNewLine); + var result = ts.createSynthesizedNode(183, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(166); + var result = ts.createSynthesizedNode(168); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(21); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(167); + var result = ts.createSynthesizedNode(169); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; } function parenthesizeForAccess(expr) { - while (expr.kind === 171 || expr.kind === 189) { + while (expr.kind === 173 || expr.kind === 191) { expr = expr.expression; } if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 169 && + expr.kind !== 171 && expr.kind !== 8) { return expr; } - var node = ts.createSynthesizedNode(172); + var node = ts.createSynthesizedNode(174); node.expression = expr; return node; } @@ -26628,7 +27084,7 @@ var ts; } function isNamespaceExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 248; + return container && container.kind !== 250; } function emitShorthandPropertyAssignment(node) { writeTextOfNode(currentText, node.name); @@ -26646,7 +27102,7 @@ var ts; if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 166 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 168 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -26657,7 +27113,7 @@ var ts; if (compilerOptions.isolatedModules) { return undefined; } - return node.kind === 166 || node.kind === 167 + return node.kind === 168 || node.kind === 169 ? resolver.getConstantValue(node) : undefined; } @@ -26740,6 +27196,9 @@ var ts; case 135: emitQualifiedNameAsExpression(node, useFallback); break; + default: + emitNodeWithoutSourceMap(node); + break; } } function emitIndexedAccess(node) { @@ -26752,10 +27211,10 @@ var ts; write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 185; }); + return ts.forEach(elements, function (e) { return e.kind === 187; }); } function skipParentheses(node) { - while (node.kind === 172 || node.kind === 171 || node.kind === 189) { + while (node.kind === 174 || node.kind === 173 || node.kind === 191) { node = node.expression; } return node; @@ -26776,12 +27235,12 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 166) { + if (expr.kind === 168) { target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 167) { + else if (expr.kind === 169) { target = emitCallTarget(expr.expression); write("["); emit(expr.argumentExpression); @@ -26822,7 +27281,7 @@ var ts; } else { emit(node.expression); - superCall = node.expression.kind === 166 && node.expression.expression.kind === 95; + superCall = node.expression.kind === 168 && node.expression.expression.kind === 95; } if (superCall && languageVersion < 2) { write(".call("); @@ -26873,21 +27332,21 @@ var ts; } } function emitParenExpression(node) { - if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 174) { - if (node.expression.kind === 171 || node.expression.kind === 189) { + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 176) { + if (node.expression.kind === 173 || node.expression.kind === 191) { var operand = node.expression.expression; - while (operand.kind === 171 || operand.kind === 189) { + while (operand.kind === 173 || operand.kind === 191) { operand = operand.expression; } - if (operand.kind !== 179 && + if (operand.kind !== 181 && + operand.kind !== 179 && + operand.kind !== 178 && operand.kind !== 177 && - operand.kind !== 176 && - operand.kind !== 175 && - operand.kind !== 180 && - operand.kind !== 169 && - !(operand.kind === 168 && node.parent.kind === 169) && - !(operand.kind === 173 && node.parent.kind === 168) && - !(operand.kind === 8 && node.parent.kind === 166)) { + operand.kind !== 182 && + operand.kind !== 171 && + !(operand.kind === 170 && node.parent.kind === 171) && + !(operand.kind === 175 && node.parent.kind === 170) && + !(operand.kind === 8 && node.parent.kind === 168)) { emit(operand); return; } @@ -26916,21 +27375,22 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 211 || node.parent.kind === 163); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 213 || node.parent.kind === 165); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, true); } function emitPrefixUnaryExpression(node) { - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); + var exportChanged = (node.operator === 41 || node.operator === 42) && + isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); if (exportChanged) { write(exportFunctionForFile + "(\""); emitNodeWithoutSourceMap(node.operand); write("\", "); } write(ts.tokenToString(node.operator)); - if (node.operand.kind === 179) { + if (node.operand.kind === 181) { var operand = node.operand; if (node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) { write(" "); @@ -26973,10 +27433,10 @@ var ts; } var current = node; while (current) { - if (current.kind === 248) { + if (current.kind === 250) { return !isExported || ((ts.getCombinedNodeFlags(node) & 2) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 219) { + else if (ts.isFunctionLike(current) || current.kind === 221) { return false; } else { @@ -26992,7 +27452,7 @@ var ts; if (ts.isElementAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(167, false); + synthesizedLHS = ts.createSynthesizedNode(169, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; if (leftHandSideExpression.argumentExpression.kind !== 8 && @@ -27009,7 +27469,7 @@ var ts; else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(166, false); + synthesizedLHS = ts.createSynthesizedNode(168, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; synthesizedLHS.dotToken = leftHandSideExpression.dotToken; @@ -27037,8 +27497,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 && node.operatorToken.kind === 56 && - (node.left.kind === 165 || node.left.kind === 164)) { - emitDestructuring(node, node.parent.kind === 195); + (node.left.kind === 167 || node.left.kind === 166)) { + emitDestructuring(node, node.parent.kind === 197); } else { var exportChanged = node.operatorToken.kind >= 56 && @@ -27090,7 +27550,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 192) { + if (node && node.kind === 194) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -27104,22 +27564,20 @@ var ts; } emitToken(15, node.pos); increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 219) { - ts.Debug.assert(node.parent.kind === 218); + if (node.kind === 221) { + ts.Debug.assert(node.parent.kind === 220); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 219) { + if (node.kind === 221) { emitTempDeclarations(true); } decreaseIndent(); writeLine(); emitToken(16, node.statements.end); - scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 192) { + if (node.kind === 194) { write(" "); emit(node); } @@ -27131,7 +27589,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 174); + emitParenthesizedIf(node.expression, node.expression.kind === 176); write(";"); } function emitIfStatement(node) { @@ -27144,7 +27602,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(80, node.thenStatement.end); - if (node.elseStatement.kind === 196) { + if (node.elseStatement.kind === 198) { write(" "); emit(node.elseStatement); } @@ -27164,7 +27622,7 @@ var ts; else { emitNormalLoopBody(node, true); } - if (node.statement.kind === 192) { + if (node.statement.kind === 194) { write(" "); } else { @@ -27255,7 +27713,7 @@ var ts; } else { var loop = convertLoopBody(node); - if (node.parent.kind === 207) { + if (node.parent.kind === 209) { emitLabelAndColon(node.parent); } loopEmitter(node, loop); @@ -27265,10 +27723,10 @@ var ts; var functionName = makeUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 199: - case 200: case 201: - if (node.initializer.kind === 212) { + case 202: + case 203: + if (node.initializer.kind === 214) { loopInitializer = node.initializer; } break; @@ -27281,7 +27739,7 @@ var ts; collectNames(varDeclaration.name); } } - var bodyIsBlock = node.statement.kind === 192; + var bodyIsBlock = node.statement.kind === 194; var paramList = loopParameters ? loopParameters.join(", ") : ""; writeLine(); write("var " + functionName + " = function(" + paramList + ")"); @@ -27296,6 +27754,9 @@ var ts; if (convertedOuterLoopState.argumentsName) { convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; } + if (convertedOuterLoopState.thisName) { + convertedLoopState.thisName = convertedOuterLoopState.thisName; + } if (convertedOuterLoopState.hoistedLocalVariables) { convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; } @@ -27317,6 +27778,15 @@ var ts; writeLine(); } } + if (convertedLoopState.thisName) { + if (convertedOuterLoopState) { + convertedOuterLoopState.thisName = convertedLoopState.thisName; + } + else { + write("var " + convertedLoopState.thisName + " = this;"); + writeLine(); + } + } if (convertedLoopState.hoistedLocalVariables) { if (convertedOuterLoopState) { convertedOuterLoopState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; @@ -27366,7 +27836,7 @@ var ts; if (emitAsEmbeddedStatement) { emitEmbeddedStatement(node.statement); } - else if (node.statement.kind === 192) { + else if (node.statement.kind === 194) { emitLines(node.statement.statements); } else { @@ -27462,7 +27932,7 @@ var ts; var endPos = emitToken(86, node.pos); write(" "); endPos = emitToken(17, endPos); - if (node.initializer && node.initializer.kind === 212) { + if (node.initializer && node.initializer.kind === 214) { var variableDeclarationList = node.initializer; var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); if (startIsEmitted) { @@ -27488,7 +27958,7 @@ var ts; } } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 && node.kind === 201) { + if (languageVersion < 2 && node.kind === 203) { emitLoop(node, emitDownLevelForOfStatementWorker); } else { @@ -27499,7 +27969,7 @@ var ts; var endPos = emitToken(86, node.pos); write(" "); endPos = emitToken(17, endPos); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 214) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); @@ -27509,7 +27979,7 @@ var ts; else { emit(node.initializer); } - if (node.kind === 200) { + if (node.kind === 202) { write(" in "); } else { @@ -27524,9 +27994,6 @@ var ts; emitNormalLoopBody(node, true); } } - function emitDownLevelForOfStatement(node) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } function emitDownLevelForOfStatementWorker(node, loop) { var endPos = emitToken(86, node.pos); write(" "); @@ -27565,7 +28032,7 @@ var ts; increaseIndent(); var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 214) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -27587,7 +28054,7 @@ var ts; } else { var assignmentExpression = createBinaryExpression(node.initializer, 56, rhsIterationValue, false); - if (node.initializer.kind === 164 || node.initializer.kind === 165) { + if (node.initializer.kind === 166 || node.initializer.kind === 167) { emitDestructuring(assignmentExpression, true, undefined); } else { @@ -27609,12 +28076,12 @@ var ts; } function emitBreakOrContinueStatement(node) { if (convertedLoopState) { - var jump = node.kind === 203 ? 2 : 4; + var jump = node.kind === 205 ? 2 : 4; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { if (!node.label) { - if (node.kind === 203) { + if (node.kind === 205) { convertedLoopState.nonLocalJumps |= 2; write("return \"break\";"); } @@ -27625,7 +28092,7 @@ var ts; } else { var labelMarker; - if (node.kind === 203) { + if (node.kind === 205) { labelMarker = "break-" + node.label.text; setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); } @@ -27638,7 +28105,7 @@ var ts; return; } } - emitToken(node.kind === 203 ? 70 : 75, node.pos); + emitToken(node.kind === 205 ? 70 : 75, node.pos); emitOptional(" ", node.label); write(";"); } @@ -27703,7 +28170,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 241) { + if (node.kind === 243) { write("case "); emit(node.expression); write(":"); @@ -27772,7 +28239,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 218); + } while (node && node.kind !== 220); return node; } function emitContainingModuleName(node) { @@ -27797,20 +28264,20 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(8); zero.text = "0"; - var result = ts.createSynthesizedNode(177); + var result = ts.createSynthesizedNode(179); result.expression = zero; return result; } function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 248) { - ts.Debug.assert(!!(node.flags & 512) || node.kind === 227); + if (node.parent.kind === 250) { + ts.Debug.assert(!!(node.flags & 512) || node.kind === 229); if (modulekind === 1 || modulekind === 2 || modulekind === 3) { if (!isEs6Module) { - if (languageVersion === 1) { + if (languageVersion !== 0) { write("Object.defineProperty(exports, \"__esModule\", { value: true });"); writeLine(); } - else if (languageVersion === 0) { + else { write("exports.__esModule = true;"); writeLine(); } @@ -27898,7 +28365,7 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(name); write("\", "); } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 || name.parent.kind === 163); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 213 || name.parent.kind === 165); if (isVariableDeclarationOrBindingElement) { emitModuleMemberName(name.parent); } @@ -27922,7 +28389,7 @@ var ts; function emitDestructuring(root, isAssignmentExpressionStatement, value) { var emitCount = 0; var canDefineTempVariablesInPlace = false; - if (root.kind === 211) { + if (root.kind === 213) { var isExported = ts.getCombinedNodeFlags(root) & 2; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; @@ -27930,7 +28397,7 @@ var ts; else if (root.kind === 138) { canDefineTempVariablesInPlace = true; } - if (root.kind === 181) { + if (root.kind === 183) { emitAssignmentExpression(root); } else { @@ -27947,14 +28414,14 @@ var ts; } function createDefaultValueCheck(value, defaultValue) { value = ensureIdentifier(value, true); - var equals = ts.createSynthesizedNode(181); + var equals = ts.createSynthesizedNode(183); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(32); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(182); + var cond = ts.createSynthesizedNode(184); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(53); cond.whenTrue = whenTrue; @@ -27982,7 +28449,7 @@ var ts; : createElementAccessExpression(object, index); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(168); + var call = ts.createSynthesizedNode(170); var sliceIdentifier = ts.createSynthesizedNode(69); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -27997,9 +28464,9 @@ var ts; } for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { var p = properties_5[_a]; - if (p.kind === 245 || p.kind === 246) { + if (p.kind === 247 || p.kind === 248) { var propName = p.name; - var target_1 = p.kind === 246 ? p : p.initializer || propName; + var target_1 = p.kind === 248 ? p : p.initializer || propName; emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName)); } } @@ -28011,8 +28478,8 @@ var ts; } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187) { - if (e.kind !== 185) { + if (e.kind !== 189) { + if (e.kind !== 187) { emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); } else if (i === elements.length - 1) { @@ -28022,20 +28489,20 @@ var ts; } } function emitDestructuringAssignment(target, value) { - if (target.kind === 246) { + if (target.kind === 248) { if (target.objectAssignmentInitializer) { value = createDefaultValueCheck(value, target.objectAssignmentInitializer); } target = target.name; } - else if (target.kind === 181 && target.operatorToken.kind === 56) { + else if (target.kind === 183 && target.operatorToken.kind === 56) { value = createDefaultValueCheck(value, target.right); target = target.left; } - if (target.kind === 165) { + if (target.kind === 167) { emitObjectLiteralAssignment(target, value); } - else if (target.kind === 164) { + else if (target.kind === 166) { emitArrayLiteralAssignment(target, value); } else { @@ -28053,14 +28520,14 @@ var ts; emitDestructuringAssignment(target, value); } else { - if (root.parent.kind !== 172) { + if (root.parent.kind !== 174) { write("("); } value = ensureIdentifier(value, true); emitDestructuringAssignment(target, value); write(", "); emit(value); - if (root.parent.kind !== 172) { + if (root.parent.kind !== 174) { write(")"); } } @@ -28081,11 +28548,11 @@ var ts; } for (var i = 0; i < numElements; i++) { var element = elements[i]; - if (pattern.kind === 161) { + if (pattern.kind === 163) { var propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } - else if (element.kind !== 187) { + else if (element.kind !== 189) { if (!element.dotDotDotToken) { emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); } @@ -28117,8 +28584,8 @@ var ts; var isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & 16384) && (getCombinedFlagsForIdentifier(node.name) & 8192); if (isLetDefinedInLoop && - node.parent.parent.kind !== 200 && - node.parent.parent.kind !== 201) { + node.parent.parent.kind !== 202 && + node.parent.parent.kind !== 203) { initializer = createVoidZero(); } } @@ -28136,7 +28603,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 187) { + if (node.kind === 189) { return; } var name = node.name; @@ -28148,7 +28615,7 @@ var ts; } } function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 211 && node.parent.kind !== 163)) { + if (!node.parent || (node.parent.kind !== 213 && node.parent.kind !== 165)) { return 0; } return ts.getCombinedNodeFlags(node.parent); @@ -28156,7 +28623,7 @@ var ts; function isES6ExportedDeclaration(node) { return !!(node.flags & 2) && modulekind === 5 && - node.parent.kind === 248; + node.parent.kind === 250; } function emitVariableStatement(node) { var startIsEmitted = false; @@ -28201,12 +28668,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_25 = createTempVariable(0); + var name_23 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_25); - emit(name_25); + tempParameters.push(name_23); + emit(name_23); } else { emit(node.name); @@ -28310,7 +28777,7 @@ var ts; emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 174 && languageVersion >= 2; + return node.kind === 176 && languageVersion >= 2; } function emitDeclarationName(node) { if (node.name) { @@ -28321,20 +28788,24 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 173) { + if (node.kind === 175) { return !!node.name; } - if (node.kind === 213) { - return !!node.name || languageVersion < 2; + if (node.kind === 215) { + return !!node.name || modulekind !== 5; } } function emitFunctionDeclaration(node) { if (ts.nodeIsMissing(node.body)) { return emitCommentsOnNotEmittedNode(node); } - if (node.kind !== 143 && node.kind !== 142 && - node.parent && node.parent.kind !== 245 && - node.parent.kind !== 168) { + var kind = node.kind, parent = node.parent; + if (kind !== 143 && + kind !== 142 && + parent && + parent.kind !== 247 && + parent.kind !== 170 && + parent.kind !== 166) { emitLeadingComments(node); } emitStart(node); @@ -28355,11 +28826,11 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (modulekind !== 5 && node.kind === 213 && node.parent === currentSourceFile && node.name) { + if (modulekind !== 5 && kind === 215 && parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } emitEnd(node); - if (node.kind !== 143 && node.kind !== 142) { + if (kind !== 143 && kind !== 142) { emitTrailingComments(node); } } @@ -28391,7 +28862,7 @@ var ts; } function emitAsyncFunctionBodyForES6(node) { var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 174; + var isArrowFunction = node.kind === 176; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096) !== 0; if (!isArrowFunction) { write(" {"); @@ -28401,17 +28872,16 @@ var ts; } write(" __awaiter(this"); if (hasLexicalArguments) { - write(", arguments"); + write(", arguments, "); } else { - write(", void 0"); + write(", void 0, "); } if (promiseConstructor) { - write(", "); - emitNodeWithoutSourceMap(promiseConstructor); + emitEntityNameAsExpression(promiseConstructor, false); } else { - write(", Promise"); + write("Promise"); } if (hasLexicalArguments) { write(", function* (_arguments)"); @@ -28433,7 +28903,7 @@ var ts; write(" { }"); } else { - if (node.body.kind === 192) { + if (node.body.kind === 194) { emitBlockFunctionBody(node, node.body); } else { @@ -28458,7 +28928,7 @@ var ts; emitSignatureParameters(node); } var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync && languageVersion === 2) { + if (isAsync) { emitAsyncFunctionBodyForES6(node); } else { @@ -28485,14 +28955,13 @@ var ts; } write(" "); var current = body; - while (current.kind === 171) { + while (current.kind === 173) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 165); + emitParenthesizedIf(body, current.kind === 167); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); emitDetachedCommentsAndUpdateCommentsInfo(node.body); @@ -28513,8 +28982,10 @@ var ts; increaseIndent(); writeLine(); emitLeadingComments(node.body); + emitStart(body); write("return "); emit(body); + emitEnd(body); write(";"); emitTrailingComments(node.body); emitTempDeclarations(true); @@ -28524,11 +28995,9 @@ var ts; emitStart(node.body); write("}"); emitEnd(node.body); - scopeEmitEnd(); } function emitBlockFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); emitDetachedCommentsAndUpdateCommentsInfo(body.statements); @@ -28555,14 +29024,13 @@ var ts; decreaseIndent(); } emitToken(16, body.statements.end); - scopeEmitEnd(); } function findInitialSuperCall(ctor) { if (ctor.body) { var statement = ctor.body.statements[0]; - if (statement && statement.kind === 195) { + if (statement && statement.kind === 197) { var expr = statement.expression; - if (expr && expr.kind === 168) { + if (expr && expr.kind === 170) { var func = expr.expression; if (func && func.kind === 95) { return statement; @@ -28645,7 +29113,7 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 191) { + if (member.kind === 193) { writeLine(); write(";"); } @@ -28742,7 +29210,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 191) { + else if (member.kind === 193) { writeLine(); write(";"); } @@ -28803,7 +29271,6 @@ var ts; } var startIndex = 0; write(" {"); - scopeEmitStart(node, "constructor"); increaseIndent(); if (ctor) { startIndex = emitDirectivePrologues(ctor.body.statements, true); @@ -28851,7 +29318,6 @@ var ts; } decreaseIndent(); emitToken(16, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); emitEnd(ctor || node); if (ctor) { emitTrailingComments(ctor); @@ -28876,7 +29342,7 @@ var ts; } function emitClassLikeDeclarationForES6AndHigher(node) { var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 214) { + if (node.kind === 216) { if (thisNodeIsDecorated) { if (isES6ExportedDeclaration(node) && !(node.flags & 512)) { write("export "); @@ -28893,7 +29359,7 @@ var ts; } } var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 186; + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 188; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0); @@ -28903,7 +29369,7 @@ var ts; write(" = "); } write("class"); - if ((node.name || (node.flags & 512 && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if ((node.name || (node.flags & 512 && (staticProperties.length > 0 || modulekind !== 5))) && !thisNodeIsDecorated) { write(" "); emitDeclarationName(node); } @@ -28914,14 +29380,12 @@ var ts; } write(" {"); increaseIndent(); - scopeEmitStart(node); writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES6AndHigher(node); decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); if (thisNodeIsDecorated) { write(";"); } @@ -28943,24 +29407,34 @@ var ts; emitPropertyDeclarations(node, staticProperties); emitDecoratorsOfClass(node); } - if (!isES6ExportedDeclaration(node) && (node.flags & 2)) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); + if (!(node.flags & 2)) { + return; } - else if (isES6ExportedDeclaration(node) && (node.flags & 512) && thisNodeIsDecorated) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); + if (modulekind !== 5) { + emitExportMemberAssignment(node); + } + else { + if (node.flags & 512) { + if (thisNodeIsDecorated) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } + } + else if (node.parent.kind !== 250) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emitDeclarationName(node); + emitEnd(node); + write(";"); + } } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 214) { + if (node.kind === 216) { if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -28984,7 +29458,6 @@ var ts; tempParameters = undefined; computedPropertyNamesToGeneratedNames = undefined; increaseIndent(); - scopeEmitStart(node); if (baseTypeNode) { writeLine(); emitStart(baseTypeNode); @@ -29015,18 +29488,17 @@ var ts; decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); emitStart(node); - write(")("); + write("("); if (baseTypeNode) { emit(baseTypeNode.expression); } - write(")"); - if (node.kind === 214) { + write("))"); + if (node.kind === 216) { write(";"); } emitEnd(node); - if (node.kind === 214) { + if (node.kind === 216) { emitExportMemberAssignment(node); } } @@ -29044,30 +29516,29 @@ var ts; function emitDecoratorsOfConstructor(node) { var decorators = node.decorators; var constructor = ts.getFirstConstructorWithBody(node); - var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated); - if (!decorators && !hasDecoratedParameters) { + var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); + if (!decorators && !firstParameterDecorator) { return; } writeLine(); - emitStart(node); + emitStart(node.decorators || firstParameterDecorator); emitDeclarationName(node); write(" = __decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); + } emitSerializedTypeMetadata(node, argumentsWritten >= 0); decreaseIndent(); writeLine(); write("], "); emitDeclarationName(node); - write(");"); - emitEnd(node); + write(")"); + emitEnd(node.decorators || firstParameterDecorator); + write(";"); writeLine(); } function emitDecoratorsOfMembers(node, staticFlag) { @@ -29079,9 +29550,6 @@ var ts; if (!ts.nodeCanBeDecorated(member)) { continue; } - if (!ts.nodeOrChildIsDecorated(member)) { - continue; - } var decorators = void 0; var functionLikeMember = void 0; if (ts.isAccessor(member)) { @@ -29101,27 +29569,27 @@ var ts; functionLikeMember = member; } } + var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); + if (!decorators && !firstParameterDecorator) { + continue; + } writeLine(); - emitStart(member); + emitStart(decorators || firstParameterDecorator); write("__decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + } emitSerializedTypeMetadata(member, argumentsWritten > 0); decreaseIndent(); writeLine(); write("], "); - emitStart(member.name); emitClassMemberPrefix(node, member); write(", "); emitExpressionForPropertyName(member.name); - emitEnd(member.name); if (languageVersion > 0) { if (member.kind !== 141) { write(", null"); @@ -29130,8 +29598,9 @@ var ts; write(", void 0"); } } - write(");"); - emitEnd(member); + write(")"); + emitEnd(decorators || firstParameterDecorator); + write(";"); writeLine(); } } @@ -29144,15 +29613,13 @@ var ts; if (ts.nodeIsDecorated(parameter)) { var decorators = parameter.decorators; argumentsWritten += emitList(decorators, 0, decorators.length, true, false, leadingComma, true, function (decorator) { - emitStart(decorator); write("__param(" + parameterIndex + ", "); emit(decorator.expression); write(")"); - emitEnd(decorator); }); leadingComma = true; } - ++parameterIndex; + parameterIndex++; } } return argumentsWritten; @@ -29176,7 +29643,7 @@ var ts; } function shouldEmitParamTypesMetadata(node) { switch (node.kind) { - case 214: + case 216: case 143: case 146: return true; @@ -29185,7 +29652,7 @@ var ts; } function emitSerializedTypeOfNode(node) { switch (node.kind) { - case 214: + case 216: write("Function"); return; case 141: @@ -29229,7 +29696,7 @@ var ts; write("Boolean"); return; case 130: - case 9: + case 162: write("String"); return; case 128: @@ -29246,6 +29713,7 @@ var ts; case 158: case 159: case 117: + case 161: break; default: ts.Debug.fail("Cannot serialize unexpected type node."); @@ -29259,8 +29727,7 @@ var ts; while (ts.isDeclaration(location) || ts.isTypeNode(location)) { location = location.parent; } - var typeName = ts.cloneEntityName(node.typeName); - typeName.parent = location; + var typeName = ts.cloneEntityName(node.typeName, location); var result = resolver.getTypeReferenceSerializationKind(typeName); switch (result) { case ts.TypeReferenceSerializationKind.Unknown: @@ -29310,7 +29777,7 @@ var ts; function emitSerializedParameterTypesOfNode(node) { if (node) { var valueDeclaration; - if (node.kind === 214) { + if (node.kind === 216) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -29400,9 +29867,10 @@ var ts; return; } if (!shouldHoistDeclarationInSystemJsModule(node)) { - if (!(node.flags & 2) || isES6ExportedDeclaration(node)) { + var isES6ExportedEnum = isES6ExportedDeclaration(node); + if (!(node.flags & 2) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 219))) { emitStart(node); - if (isES6ExportedDeclaration(node)) { + if (isES6ExportedEnum) { write("export "); } write("var "); @@ -29419,12 +29887,10 @@ var ts; emitEnd(node.name); write(") {"); increaseIndent(); - scopeEmitStart(node); emitLines(node.members); decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); write(")("); emitModuleMemberName(node); write(" || ("); @@ -29482,7 +29948,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 218) { + if (moduleDeclaration.body.kind === 220) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -29493,6 +29959,9 @@ var ts; function isModuleMergedWithES6Class(node) { return languageVersion === 2 && !!(resolver.getNodeCheckFlags(node) & 32768); } + function isFirstDeclarationOfKind(node, declarations, kind) { + return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); + } function emitModuleDeclaration(node) { var shouldEmit = shouldEmitModuleDeclaration(node); if (!shouldEmit) { @@ -29501,15 +29970,18 @@ var ts; var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); if (emitVarForModule) { - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); + var isES6ExportedNamespace = isES6ExportedDeclaration(node); + if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 220)) { + emitStart(node); + if (isES6ExportedNamespace) { + write("export "); + } + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); } emitStart(node); write("(function ("); @@ -29517,7 +29989,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 219) { + if (node.body.kind === 221) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; @@ -29533,7 +30005,6 @@ var ts; else { write("{"); increaseIndent(); - scopeEmitStart(node); emitCaptureThisForNodeIfNecessary(node); writeLine(); emit(node.body); @@ -29541,7 +30012,6 @@ var ts; writeLine(); var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; emitToken(16, moduleBlock.statements.end); - scopeEmitEnd(); } write(")("); if ((node.flags & 2) && !isES6ExportedDeclaration(node)) { @@ -29590,16 +30060,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 221) { + if (node.kind === 223) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 226) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 222 && node.importClause && !!node.importClause.name; + return node.kind === 224 && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -29626,7 +30096,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 224) { + if (node.importClause.namedBindings.kind === 226) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -29652,7 +30122,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 && (node.flags & 2) !== 0; + var isExportedImport = node.kind === 223 && (node.flags & 2) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (modulekind !== 2) { emitLeadingComments(node); @@ -29664,7 +30134,7 @@ var ts; write(" = "); } else { - var isNakedImport = 222 && !node.importClause; + var isNakedImport = 224 && !node.importClause; if (!isNakedImport) { write("var "); write(getGeneratedNameForNode(node)); @@ -29771,15 +30241,17 @@ var ts; } } else { - writeLine(); - write("__export("); - if (modulekind !== 2) { - emitRequire(ts.getExternalModuleName(node)); + if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + writeLine(); + write("__export("); + if (modulekind !== 2) { + emitRequire(ts.getExternalModuleName(node)); + } + else { + write(generatedName); + } + write(");"); } - else { - write(generatedName); - } - write(");"); } emitEnd(node); } @@ -29829,8 +30301,8 @@ var ts; write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 213 && - expression.kind !== 214) { + if (expression.kind !== 215 && + expression.kind !== 216) { write(";"); } emitEnd(node); @@ -29863,26 +30335,28 @@ var ts; externalImports = []; exportSpecifiers = {}; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 222: + case 224: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, true)) { externalImports.push(node); } break; - case 221: - if (node.moduleReference.kind === 232 && resolver.isReferencedAliasDeclaration(node)) { + case 223: + if (node.moduleReference.kind === 234 && resolver.isReferencedAliasDeclaration(node)) { externalImports.push(node); } break; - case 228: + case 230: if (node.moduleSpecifier) { if (!node.exportClause) { - externalImports.push(node); - hasExportStars = true; + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } } else if (resolver.isValueAliasDeclaration(node)) { externalImports.push(node); @@ -29891,12 +30365,12 @@ var ts; else { for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_26 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_26] || (exportSpecifiers[name_26] = [])).push(specifier); + var name_24 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_24] || (exportSpecifiers[name_24] = [])).push(specifier); } } break; - case 227: + case 229: if (node.isExportEquals && !exportEquals) { exportEquals = node; } @@ -29905,7 +30379,7 @@ var ts; } } function emitExportStarHelper() { - if (hasExportStars) { + if (hasExportStarsToExportValues) { writeLine(); write("function __export(m) {"); increaseIndent(); @@ -29921,14 +30395,20 @@ var ts; if (namespaceDeclaration && !isDefaultImport(node)) { return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); } - if (node.kind === 222 && node.importClause) { + if (node.kind === 224 && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 228 && node.moduleSpecifier) { + if (node.kind === 230 && node.moduleSpecifier) { return getGeneratedNameForNode(node); } } - function getExternalModuleNameText(importNode) { + function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { + if (emitRelativePathAsModuleName) { + var name_25 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_25) { + return "\"" + name_25 + "\""; + } + } var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9) { return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); @@ -29943,8 +30423,8 @@ var ts; var started = false; for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { var importNode = externalImports_1[_a]; - var skipNode = importNode.kind === 228 || - (importNode.kind === 222 && !importNode.importClause); + var skipNode = importNode.kind === 230 || + (importNode.kind === 224 && !importNode.importClause); if (skipNode) { continue; } @@ -29962,14 +30442,14 @@ var ts; } } function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) { - if (!hasExportStars) { + if (!hasExportStarsToExportValues) { return undefined; } if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; - if (externalImport.kind === 228 && externalImport.exportClause) { + if (externalImport.kind === 230 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -29984,7 +30464,7 @@ var ts; increaseIndent(); var started = false; if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; ++i) { + for (var i = 0; i < exportedDeclarations.length; i++) { writeExportedName(exportedDeclarations[i]); } } @@ -29998,7 +30478,7 @@ var ts; } for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 228) { + if (externalImport.kind !== 230) { continue; } var exportDecl = externalImport; @@ -30070,13 +30550,13 @@ var ts; writeLine(); write("var "); var seen = {}; - for (var i = 0; i < hoistedVars.length; ++i) { + for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_27 = local.kind === 69 + var name_26 = local.kind === 69 ? local : local.name; - if (name_27) { - var text = ts.unescapeIdentifier(name_27.text); + if (name_26) { + var text = ts.unescapeIdentifier(name_26.text); if (ts.hasProperty(seen, text)) { continue; } @@ -30087,7 +30567,7 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 214 || local.kind === 218 || local.kind === 217) { + if (local.kind === 216 || local.kind === 220 || local.kind === 219) { emitDeclarationName(local); } else { @@ -30121,21 +30601,21 @@ var ts; if (node.flags & 4) { return; } - if (node.kind === 213) { + if (node.kind === 215) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 214) { + if (node.kind === 216) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 217) { + if (node.kind === 219) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -30144,7 +30624,7 @@ var ts; } return; } - if (node.kind === 218) { + if (node.kind === 220) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -30153,17 +30633,17 @@ var ts; } return; } - if (node.kind === 211 || node.kind === 163) { + if (node.kind === 213 || node.kind === 165) { if (shouldHoistVariable(node, false)) { - var name_28 = node.name; - if (name_28.kind === 69) { + var name_27 = node.name; + if (name_27.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_28); + hoistedVars.push(name_27); } else { - ts.forEachChild(name_28, visit); + ts.forEachChild(name_27, visit); } } return; @@ -30189,7 +30669,7 @@ var ts; return false; } return (ts.getCombinedNodeFlags(node) & 24576) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 248; + ts.getEnclosingBlockScopeContainer(node).kind === 250; } function isCurrentFileSystemExternalModule() { return modulekind === 4 && isCurrentFileExternalModule; @@ -30213,7 +30693,7 @@ var ts; } function emitSetters(exportStarFunction, dependencyGroups) { write("setters:["); - for (var i = 0; i < dependencyGroups.length; ++i) { + for (var i = 0; i < dependencyGroups.length; i++) { if (i !== 0) { write(","); } @@ -30227,24 +30707,24 @@ var ts; var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { - case 222: + case 224: if (!entry.importClause) { break; } - case 221: + case 223: ts.Debug.assert(importVariableName !== ""); writeLine(); write(importVariableName + " = " + parameterName + ";"); writeLine(); break; - case 228: + case 230: ts.Debug.assert(importVariableName !== ""); if (entry.exportClause) { writeLine(); write(exportFunctionForFile + "({"); writeLine(); increaseIndent(); - for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) { + for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; i_2++) { if (i_2 !== 0) { write(","); writeLine(); @@ -30278,13 +30758,13 @@ var ts; write("execute: function() {"); increaseIndent(); writeLine(); - for (var i = startIndex; i < node.statements.length; ++i) { + for (var i = startIndex; i < node.statements.length; i++) { var statement = node.statements[i]; switch (statement.kind) { - case 213: - case 222: + case 215: + case 224: continue; - case 228: + case 230: if (!statement.moduleSpecifier) { for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { var element = _b[_a]; @@ -30292,7 +30772,7 @@ var ts; } } continue; - case 221: + case 223: if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { continue; } @@ -30321,8 +30801,8 @@ var ts; write("["); var groupIndices = {}; var dependencyGroups = []; - for (var i = 0; i < externalImports.length; ++i) { - var text = getExternalModuleNameText(externalImports[i]); + for (var i = 0; i < externalImports.length; i++) { + var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); if (ts.hasProperty(groupIndices, text)) { var groupIndex = groupIndices[text]; dependencyGroups[groupIndex].push(externalImports[i]); @@ -30335,18 +30815,12 @@ var ts; if (i !== 0) { write(", "); } - if (emitRelativePathAsModuleName) { - var name_29 = getExternalModuleNameFromDeclaration(host, resolver, externalImports[i]); - if (name_29) { - text = "\"" + name_29 + "\""; - } - } write(text); } write("], function(" + exportFunctionForFile + ") {"); writeLine(); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, true); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitSystemModuleBody(node, dependencyGroups, startIndex); @@ -30370,13 +30844,7 @@ var ts; } for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { var importNode = externalImports_4[_c]; - var externalModuleName = getExternalModuleNameText(importNode); - if (emitRelativePathAsModuleName) { - var name_30 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_30) { - externalModuleName = "\"" + name_30 + "\""; - } - } + var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); var importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { aliasedModuleNames.push(externalModuleName); @@ -30424,7 +30892,7 @@ var ts; writeModuleName(node, emitRelativePathAsModuleName); emitAMDDependencies(node, true, emitRelativePathAsModuleName); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -30435,7 +30903,7 @@ var ts; write("});"); } function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, false); + var startIndex = emitDirectivePrologues(node.statements, false, true); emitEmitHelpers(node); collectExternalModuleInfo(node); emitExportStarHelper(); @@ -30454,7 +30922,7 @@ var ts; writeLines(" }\n})("); emitAMDFactoryHeader(dependencyNames); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -30468,7 +30936,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; var startIndex = emitDirectivePrologues(node.statements, false); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); @@ -30524,7 +30992,8 @@ var ts; if (result) { result = result.replace(/&(\w+);/g, function (s, m) { if (entities[m] !== undefined) { - return String.fromCharCode(entities[m]); + var ch = String.fromCharCode(entities[m]); + return ch === "\"" ? "\\\"" : ch; } else { return s; @@ -30576,23 +31045,40 @@ var ts; } } } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { + function isUseStrictPrologue(node) { + return !!node.expression.text.match(/use strict/); + } + function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { + if (writeUseStrict) { + if (startWithNewLine) { + writeLine(); + } + write("\"use strict\";"); + } + } + function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { + var foundUseStrict = false; + for (var i = 0; i < statements.length; i++) { if (ts.isPrologueDirective(statements[i])) { + if (isUseStrictPrologue(statements[i])) { + foundUseStrict = true; + } if (startWithNewLine || i > 0) { writeLine(); } emit(statements[i]); } else { + ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); return i; } } + ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); return statements.length; } function writeLines(text) { var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; ++i) { + for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (line.length) { writeLine(); @@ -30628,7 +31114,7 @@ var ts; emitShebang(); emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - if (root || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { + if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1]; emitModule(node); } @@ -30641,7 +31127,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -30649,6 +31135,9 @@ var ts; } emitLeadingComments(node.endOfFileToken); } + function emit(node) { + emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); + } function emitNodeWithCommentsAndWithoutSourcemap(node) { emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); } @@ -30670,6 +31159,13 @@ var ts; } } } + function emitNodeWithSourceMap(node) { + if (node) { + emitStart(node); + emitNodeWithoutSourceMap(node); + emitEnd(node); + } + } function emitNodeWithoutSourceMap(node) { if (node) { emitJavaScriptWorker(node); @@ -30677,28 +31173,28 @@ var ts; } function isSpecializedCommentHandling(node) { switch (node.kind) { + case 217: case 215: - case 213: - case 222: - case 221: - case 216: - case 227: + case 224: + case 223: + case 218: + case 229: return true; } } function shouldEmitLeadingAndTrailingComments(node) { switch (node.kind) { - case 193: + case 195: return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 218: + case 220: return shouldEmitModuleDeclaration(node); - case 217: + case 219: return shouldEmitEnumDeclaration(node); } ts.Debug.assert(!isSpecializedCommentHandling(node)); - if (node.kind !== 192 && + if (node.kind !== 194 && node.parent && - node.parent.kind === 174 && + node.parent.kind === 176 && node.parent.body === node && compilerOptions.target <= 1) { return false; @@ -30735,142 +31231,142 @@ var ts; case 13: case 14: return emitLiteral(node); - case 183: + case 185: return emitTemplateExpression(node); - case 190: + case 192: return emitTemplateSpan(node); - case 233: - case 234: - return emitJsxElement(node); + case 235: case 236: + return emitJsxElement(node); + case 238: return emitJsxText(node); - case 240: + case 242: return emitJsxExpression(node); case 135: return emitQualifiedName(node); - case 161: - return emitObjectBindingPattern(node); - case 162: - return emitArrayBindingPattern(node); case 163: - return emitBindingElement(node); + return emitObjectBindingPattern(node); case 164: - return emitArrayLiteral(node); + return emitArrayBindingPattern(node); case 165: + return emitBindingElement(node); + case 166: + return emitArrayLiteral(node); + case 167: return emitObjectLiteral(node); - case 245: + case 247: return emitPropertyAssignment(node); - case 246: + case 248: return emitShorthandPropertyAssignment(node); case 136: return emitComputedPropertyName(node); - case 166: - return emitPropertyAccess(node); - case 167: - return emitIndexedAccess(node); case 168: - return emitCallExpression(node); + return emitPropertyAccess(node); case 169: - return emitNewExpression(node); + return emitIndexedAccess(node); case 170: - return emitTaggedTemplateExpression(node); + return emitCallExpression(node); case 171: - return emit(node.expression); - case 189: - return emit(node.expression); + return emitNewExpression(node); case 172: - return emitParenExpression(node); - case 213: + return emitTaggedTemplateExpression(node); case 173: + return emit(node.expression); + case 191: + return emit(node.expression); case 174: - return emitFunctionDeclaration(node); - case 175: - return emitDeleteExpression(node); - case 176: - return emitTypeOfExpression(node); - case 177: - return emitVoidExpression(node); - case 178: - return emitAwaitExpression(node); - case 179: - return emitPrefixUnaryExpression(node); - case 180: - return emitPostfixUnaryExpression(node); - case 181: - return emitBinaryExpression(node); - case 182: - return emitConditionalExpression(node); - case 185: - return emitSpreadElementExpression(node); - case 184: - return emitYieldExpression(node); - case 187: - return; - case 192: - case 219: - return emitBlock(node); - case 193: - return emitVariableStatement(node); - case 194: - return write(";"); - case 195: - return emitExpressionStatement(node); - case 196: - return emitIfStatement(node); - case 197: - return emitDoStatement(node); - case 198: - return emitWhileStatement(node); - case 199: - return emitForStatement(node); - case 201: - case 200: - return emitForInOrForOfStatement(node); - case 202: - case 203: - return emitBreakOrContinueStatement(node); - case 204: - return emitReturnStatement(node); - case 205: - return emitWithStatement(node); - case 206: - return emitSwitchStatement(node); - case 241: - case 242: - return emitCaseOrDefaultClause(node); - case 207: - return emitLabeledStatement(node); - case 208: - return emitThrowStatement(node); - case 209: - return emitTryStatement(node); - case 244: - return emitCatchClause(node); - case 210: - return emitDebuggerStatement(node); - case 211: - return emitVariableDeclaration(node); - case 186: - return emitClassExpression(node); - case 214: - return emitClassDeclaration(node); + return emitParenExpression(node); case 215: - return emitInterfaceDeclaration(node); - case 217: - return emitEnumDeclaration(node); - case 247: - return emitEnumMember(node); - case 218: - return emitModuleDeclaration(node); - case 222: - return emitImportDeclaration(node); + case 175: + case 176: + return emitFunctionDeclaration(node); + case 177: + return emitDeleteExpression(node); + case 178: + return emitTypeOfExpression(node); + case 179: + return emitVoidExpression(node); + case 180: + return emitAwaitExpression(node); + case 181: + return emitPrefixUnaryExpression(node); + case 182: + return emitPostfixUnaryExpression(node); + case 183: + return emitBinaryExpression(node); + case 184: + return emitConditionalExpression(node); + case 187: + return emitSpreadElementExpression(node); + case 186: + return emitYieldExpression(node); + case 189: + return; + case 194: case 221: + return emitBlock(node); + case 195: + return emitVariableStatement(node); + case 196: + return write(";"); + case 197: + return emitExpressionStatement(node); + case 198: + return emitIfStatement(node); + case 199: + return emitDoStatement(node); + case 200: + return emitWhileStatement(node); + case 201: + return emitForStatement(node); + case 203: + case 202: + return emitForInOrForOfStatement(node); + case 204: + case 205: + return emitBreakOrContinueStatement(node); + case 206: + return emitReturnStatement(node); + case 207: + return emitWithStatement(node); + case 208: + return emitSwitchStatement(node); + case 243: + case 244: + return emitCaseOrDefaultClause(node); + case 209: + return emitLabeledStatement(node); + case 210: + return emitThrowStatement(node); + case 211: + return emitTryStatement(node); + case 246: + return emitCatchClause(node); + case 212: + return emitDebuggerStatement(node); + case 213: + return emitVariableDeclaration(node); + case 188: + return emitClassExpression(node); + case 216: + return emitClassDeclaration(node); + case 217: + return emitInterfaceDeclaration(node); + case 219: + return emitEnumDeclaration(node); + case 249: + return emitEnumMember(node); + case 220: + return emitModuleDeclaration(node); + case 224: + return emitImportDeclaration(node); + case 223: return emitImportEqualsDeclaration(node); - case 228: + case 230: return emitExportDeclaration(node); - case 227: + case 229: return emitExportAssignment(node); - case 248: + case 250: return emitSourceFileNode(node); } } @@ -30900,7 +31396,7 @@ var ts; } function getLeadingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 248 || node.pos !== node.parent.pos) { + if (node.parent.kind === 250 || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { return getLeadingCommentsWithoutDetachedComments(); } @@ -30912,7 +31408,7 @@ var ts; } function getTrailingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 248 || node.end !== node.parent.end) { + if (node.parent.kind === 250 || node.end !== node.parent.end) { return ts.getTrailingCommentRanges(currentText, node.end); } } @@ -30978,18 +31474,30 @@ var ts; } } } + function writeComment(text, lineMap, writer, comment, newLine) { + emitPos(comment.pos); + ts.writeCommentRange(text, lineMap, writer, comment, newLine); + emitPos(comment.end); + } function emitShebang() { var shebang = ts.getShebang(currentText); if (shebang) { write(shebang); + writeLine(); } } var _a, _b; } - function emitFile(jsFilePath, sourceFile) { - emitJavaScript(jsFilePath, sourceFile); - if (compilerOptions.declaration) { - ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics); + function emitFile(_a, sourceFiles, isBundledEmit) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; + } + if (declarationFilePath) { + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } } } @@ -31003,10 +31511,10 @@ var ts; ts.ioWriteTime = 0; var emptyArray = []; ts.version = "1.8.0"; - function findConfigFile(searchPath) { + function findConfigFile(searchPath, fileExists) { var fileName = "tsconfig.json"; while (true) { - if (ts.sys.fileExists(fileName)) { + if (fileExists(fileName)) { return fileName; } var parentPath = ts.getDirectoryPath(searchPath); @@ -31030,21 +31538,22 @@ var ts; ? compilerOptions.moduleResolution : compilerOptions.module === 1 ? 2 : 1; switch (moduleResolution) { - case 2: return nodeModuleNameResolver(moduleName, containingFile, host); + case 2: return nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); case 1: return classicNameResolver(moduleName, containingFile, compilerOptions, host); } } ts.resolveModuleName = resolveModuleName; - function nodeModuleNameResolver(moduleName, containingFile, host) { + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { var failedLookupLocations = []; var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolvedFileName = loadNodeModuleFromFile(ts.supportedJsExtensions, candidate, failedLookupLocations, host); + var resolvedFileName = loadNodeModuleFromFile(supportedExtensions, candidate, failedLookupLocations, false, host); if (resolvedFileName) { return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }; } - resolvedFileName = loadNodeModuleFromDirectory(ts.supportedJsExtensions, candidate, failedLookupLocations, host); + resolvedFileName = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, false, host); return resolvedFileName ? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations } : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; @@ -31054,11 +31563,15 @@ var ts; } } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, host) { + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, onlyRecordFailures, host) { return ts.forEach(extensions, tryLoad); function tryLoad(ext) { var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (host.fileExists(fileName)) { + if (!onlyRecordFailures && host.fileExists(fileName)) { return fileName; } else { @@ -31067,9 +31580,10 @@ var ts; } } } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, host) { + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, host) { var packageJsonPath = ts.combinePaths(candidate, "package.json"); - if (host.fileExists(packageJsonPath)) { + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, host); + if (directoryExists && host.fileExists(packageJsonPath)) { var jsonContent; try { var jsonText = host.readFile(packageJsonPath); @@ -31078,8 +31592,9 @@ var ts; catch (e) { jsonContent = { typings: undefined }; } - if (jsonContent.typings) { - var result = loadNodeModuleFromFile(extensions, ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host); + if (typeof jsonContent.typings === "string") { + var path = ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)); + var result = loadNodeModuleFromFile(extensions, path, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(path), host), host); if (result) { return result; } @@ -31088,7 +31603,7 @@ var ts; else { failedLookupLocation.push(packageJsonPath); } - return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, host); + return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, !directoryExists, host); } function loadModuleFromNodeModules(moduleName, directory, host) { var failedLookupLocations = []; @@ -31097,12 +31612,13 @@ var ts; var baseName = ts.getBaseFileName(directory); if (baseName !== "node_modules") { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, host); var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var result = loadNodeModuleFromFile(ts.supportedExtensions, candidate, failedLookupLocations, host); + var result = loadNodeModuleFromFile(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; } - result = loadNodeModuleFromDirectory(ts.supportedExtensions, candidate, failedLookupLocations, host); + result = loadNodeModuleFromDirectory(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; } @@ -31127,10 +31643,10 @@ var ts; var searchName; var failedLookupLocations = []; var referencedSourceFile; - var extensions = compilerOptions.allowNonTsExtensions ? ts.supportedJsExtensions : ts.supportedExtensions; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); while (true) { searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - referencedSourceFile = ts.forEach(extensions, function (extension) { + referencedSourceFile = ts.forEach(supportedExtensions, function (extension) { if (extension === ".tsx" && !compilerOptions.jsx) { return undefined; } @@ -31225,14 +31741,15 @@ var ts; getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); } + readFile: function (fileName) { return ts.sys.readFile(fileName); }, + directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); } }; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -31270,8 +31787,10 @@ var ts; var noDiagnosticsTypeChecker; var classifiableNames; var skipDefaultLib = options.noLib; + var supportedExtensions = ts.getSupportedExtensions(options); var start = new Date().getTime(); host = host || createCompilerHost(options); + var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var currentDirectory = host.getCurrentDirectory(); var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) @@ -31284,7 +31803,8 @@ var ts; (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx)) { + (oldOptions.jsx !== options.jsx) || + (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } @@ -31294,9 +31814,7 @@ var ts; processRootFile(host.getDefaultLibFileName(options), true); } } - verifyCompilerOptions(); oldProgram = undefined; - ts.programTime += new Date().getTime() - start; program = { getRootFileNames: function () { return rootNames; }, getSourceFile: getSourceFile, @@ -31310,7 +31828,7 @@ var ts; getTypeChecker: getTypeChecker, getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, - getCommonSourceDirectory: function () { return commonSourceDirectory; }, + getCommonSourceDirectory: getCommonSourceDirectory, emit: emit, getCurrentDirectory: function () { return currentDirectory; }, getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, @@ -31319,7 +31837,23 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; } }; + verifyCompilerOptions(); + ts.programTime += new Date().getTime() - start; return program; + function getCommonSourceDirectory() { + if (typeof commonSourceDirectory === "undefined") { + if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(files); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); @@ -31365,7 +31899,7 @@ var ts; if (resolveModuleNamesWorker) { var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); - for (var i = 0; i < moduleNames.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var newResolution = resolutions[i]; var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); var resolutionChanged = oldResolution @@ -31386,7 +31920,7 @@ var ts; } newSourceFiles.push(newSourceFile); } - for (var i = 0, len = newSourceFiles.length; i < len; ++i) { + for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; @@ -31407,7 +31941,8 @@ var ts; getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFiles: program.getSourceFiles, - writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }) + writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }), + isEmitBlocked: isEmitBlocked }; } function getDiagnosticsProducingTypeChecker() { @@ -31420,9 +31955,15 @@ var ts; var _this = this; return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { - if (options.noEmitOnError && getPreEmitDiagnostics(program, undefined, cancellationToken).length > 0) { - return { diagnostics: [], sourceMaps: undefined, emitSkipped: true }; + if (options.noEmitOnError) { + var preEmitDiagnostics = getPreEmitDiagnostics(program, undefined, cancellationToken); + if (preEmitDiagnostics.length > 0) { + return { diagnostics: preEmitDiagnostics, sourceMaps: undefined, emitSkipped: true }; + } } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); var start = new Date().getTime(); @@ -31475,12 +32016,160 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? + getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : + typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); } + function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var diagnostics = []; + walk(sourceFile); + return diagnostics; + function walk(node) { + if (!node) { + return false; + } + switch (node.kind) { + case 223: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return true; + case 229: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return true; + case 216: + var classDeclaration = node; + if (checkModifiers(classDeclaration.modifiers) || + checkTypeParameters(classDeclaration.typeParameters)) { + return true; + } + break; + case 245: + var heritageClause = node; + if (heritageClause.token === 106) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 217: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 220: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 218: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return true; + case 143: + case 142: + case 144: + case 145: + case 146: + case 175: + case 215: + case 176: + case 215: + var functionDeclaration = node; + if (checkModifiers(functionDeclaration.modifiers) || + checkTypeParameters(functionDeclaration.typeParameters) || + checkTypeAnnotation(functionDeclaration.type)) { + return true; + } + break; + case 195: + var variableStatement = node; + if (checkModifiers(variableStatement.modifiers)) { + return true; + } + break; + case 213: + var variableDeclaration = node; + if (checkTypeAnnotation(variableDeclaration.type)) { + return true; + } + break; + case 170: + case 171: + 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)); + return true; + } + break; + case 138: + 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)); + return true; + } + if (parameter.questionToken) { + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return true; + } + if (parameter.type) { + diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 141: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 219: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 173: + var typeAssertionExpression = node; + diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return true; + case 139: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); + return true; + } + return ts.forEachChild(node, walk); + } + 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)); + return true; + } + return false; + } + function checkTypeAnnotation(type) { + if (type) { + diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkModifiers(modifiers) { + if (modifiers) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 112: + case 110: + case 111: + case 122: + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + case 113: + case 82: + case 74: + case 77: + case 115: + } + } + } + return false; + } + }); + } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { return runWithCancellationToken(function () { if (!ts.isDeclarationFile(sourceFile)) { @@ -31528,9 +32217,9 @@ var ts; function collect(node, allowRelativeModuleNames, collectOnlyRequireCalls) { if (!collectOnlyRequireCalls) { switch (node.kind) { - case 222: - case 221: - case 228: + case 224: + case 223: + case 230: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9) { break; @@ -31542,7 +32231,7 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 218: + case 220: if (node.name.kind === 9 && (node.flags & 4 || ts.isDeclarationFile(file))) { ts.forEachChild(node.body, function (node) { collect(node, false, collectOnlyRequireCalls); @@ -31565,9 +32254,9 @@ var ts; var diagnosticArgument; var diagnostic; if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; + diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; @@ -31585,7 +32274,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -31609,10 +32298,10 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function findSourceFile(fileName, normalizedAbsolutePath, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(normalizedAbsolutePath)) { - var file_1 = filesByName.get(normalizedAbsolutePath); - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== normalizedAbsolutePath) { + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + if (filesByName.contains(path)) { + var file_1 = filesByName.get(path); + if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } return file_1; @@ -31625,16 +32314,16 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); - filesByName.set(normalizedAbsolutePath, file); + filesByName.set(path, file); if (file) { - file.path = normalizedAbsolutePath; + file.path = path; if (host.useCaseSensitiveFileNames()) { - var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); + var existingFile = filesByNameIgnoreCase.get(path); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(normalizedAbsolutePath, file); + filesByNameIgnoreCase.set(path, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -31667,15 +32356,15 @@ var ts; file.resolvedModules = {}; var moduleNames = ts.map(file.imports, function (name) { return name.text; }); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); - for (var i = 0; i < file.imports.length; ++i) { + for (var i = 0; i < file.imports.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); if (resolution && !options.noResolve) { var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { if (!ts.isExternalModule(importedFile)) { - var start_2 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_2, file.imports[i].end - start_2, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); + var start_5 = ts.getTokenPosOfNode(file.imports[i], file); + fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { var firstRef = importedFile.referencedFiles[0]; @@ -31692,7 +32381,7 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var commonPathComponents; - ts.forEach(files, function (sourceFile) { + var failed = ts.forEach(files, function (sourceFile) { if (ts.isDeclarationFile(sourceFile)) { return; } @@ -31703,10 +32392,9 @@ var ts; return; } for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; + return true; } commonPathComponents.length = i; break; @@ -31716,6 +32404,9 @@ var ts; commonPathComponents.length = sourcePathComponents.length; } }); + if (failed) { + return ""; + } if (!commonPathComponents) { return currentDirectory; } @@ -31725,8 +32416,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -31760,14 +32451,14 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); } - if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap")); - } } if (options.inlineSources) { if (!options.sourceMap && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); } + if (options.sourceRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); + } } if (options.out && options.outFile) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); @@ -31776,10 +32467,9 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } - if (options.sourceRoot) { + if (options.sourceRoot && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); } - return; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; @@ -31796,7 +32486,7 @@ var ts; } else if (firstExternalModuleSourceFile && languageVersion < 2 && !options.module) { var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } if (options.module === 5 && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); @@ -31807,14 +32497,9 @@ var ts; if (options.outDir || options.sourceRoot || options.mapRoot) { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { - commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); - } - else { - commonSourceDirectory = computeCommonSourceDirectory(files); - } - if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { - commonSourceDirectory += ts.directorySeparator; + var dir = getCommonSourceDirectory(); + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { @@ -31831,10 +32516,42 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } + else if (options.allowJs && options.declaration) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } + if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + } + if (!options.noEmit) { + var emitHost = getEmitHost(); + var emitFilesSeen = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen); + }); + } + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); + if (filesByName.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + } + if (emitFilesSeen.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + } + else { + emitFilesSeen.set(emitFilePath, true); + } + } + } + } + function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); } } ts.createProgram = createProgram; @@ -31889,6 +32606,11 @@ var ts; description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, error: ts.Diagnostics.Argument_for_jsx_must_be_preserve_or_react }, + { + name: "reactNamespace", + type: "string", + description: ts.Diagnostics.Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit + }, { name: "listFiles", type: "boolean" @@ -32113,6 +32835,16 @@ var ts; name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "allowJs", + type: "boolean", + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled } ]; var optionNameMapCache; @@ -32146,7 +32878,8 @@ var ts; function parseStrings(args) { var i = 0; while (i < args.length) { - var s = args[i++]; + var s = args[i]; + i++; if (s.charCodeAt(0) === 64) { parseResponseFile(s.slice(1)); } @@ -32162,19 +32895,22 @@ var ts; } switch (opt.type) { case "number": - options[opt.name] = parseInt(args[i++]); + options[opt.name] = parseInt(args[i]); + i++; break; case "boolean": options[opt.name] = true; break; case "string": - options[opt.name] = args[i++] || ""; + options[opt.name] = args[i] || ""; + i++; break; default: - var map_2 = opt.type; - var key = (args[i++] || "").toLowerCase(); - if (ts.hasProperty(map_2, key)) { - options[opt.name] = map_2[key]; + var map_1 = opt.type; + var key = (args[i] || "").toLowerCase(); + i++; + if (ts.hasProperty(map_1, key)) { + options[opt.name] = map_1[key]; } else { errors.push(ts.createCompilerDiagnostic(opt.error)); @@ -32264,8 +33000,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath) { - var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors; + function parseJsonConfigFileContent(json, host, basePath, existingOptions) { + if (existingOptions === void 0) { existingOptions = {}; } + var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), optionsFromJsonConfigFile = _a.options, errors = _a.errors; + var options = ts.extend(existingOptions, optionsFromJsonConfigFile); return { options: options, fileNames: getFileNames(), @@ -32282,23 +33020,26 @@ var ts; } } else { + var filesSeen = {}; var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; - var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); - for (var i = 0; i < sysFiles.length; i++) { - var name_31 = sysFiles[i]; - if (ts.fileExtensionIs(name_31, ".d.ts")) { - var baseName = name_31.substr(0, name_31.length - ".d.ts".length); - if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) { - fileNames.push(name_31); + var supportedExtensions = ts.getSupportedExtensions(options); + ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); + for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; + var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); + for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { + var fileName = filesInDirWithExtension_1[_a]; + if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { + continue; } - } - else if (ts.fileExtensionIs(name_31, ".ts")) { - if (!ts.contains(sysFiles, name_31 + "x")) { - fileNames.push(name_31); + if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { + var baseName = fileName.substr(0, fileName.length - extension.length); + if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { + continue; + } } - } - else { - fileNames.push(name_31); + filesSeen[fileName] = true; + fileNames.push(fileName); } } } @@ -32562,7 +33303,7 @@ var ts; return ts.sys.exit(ts.ExitStatus.Success); } if (commandLine.options.version) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Version_0, ts.version), undefined); + printVersion(); return ts.sys.exit(ts.ExitStatus.Success); } if (commandLine.options.help) { @@ -32575,15 +33316,29 @@ var ts; reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--project"), undefined); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } - configFileName = ts.normalizePath(ts.combinePaths(commandLine.options.project, "tsconfig.json")); if (commandLine.fileNames.length !== 0) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line), undefined); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } + var fileOrDirectory = ts.normalizePath(commandLine.options.project); + if (!fileOrDirectory || ts.sys.directoryExists(fileOrDirectory)) { + configFileName = ts.combinePaths(fileOrDirectory, "tsconfig.json"); + if (!ts.sys.fileExists(configFileName)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project), undefined); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + } + else { + configFileName = fileOrDirectory; + if (!ts.sys.fileExists(configFileName)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project), undefined); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + } } else if (commandLine.fileNames.length === 0 && isJSONSupported()) { var searchPath = ts.normalizePath(ts.sys.getCurrentDirectory()); - configFileName = ts.findConfigFile(searchPath); + configFileName = ts.findConfigFile(searchPath, ts.sys.fileExists); } if (commandLine.fileNames.length === 0 && !configFileName) { printVersion(); @@ -32629,7 +33384,7 @@ var ts; ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); return; } - var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getDirectoryPath(configFileName)); + var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getDirectoryPath(configFileName), commandLine.options); if (configParseResult.errors.length > 0) { reportDiagnostics(configParseResult.errors, undefined); ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); @@ -32642,7 +33397,7 @@ var ts; if (configFileName) { var configParseResult = parseConfigFile(); rootFileNames = configParseResult.fileNames; - compilerOptions = ts.extend(commandLine.options, configParseResult.options); + compilerOptions = configParseResult.options; } else { rootFileNames = commandLine.fileNames; @@ -32715,7 +33470,7 @@ var ts; startTimerForRecompilation(); } function watchedDirectoryChanged(fileName) { - if (fileName && !ts.isSupportedSourceFileName(fileName)) { + if (fileName && !ts.isSupportedSourceFileName(fileName, commandLine.options)) { return; } startTimerForHandlingDirectoryChanges(); @@ -32891,10 +33646,10 @@ var ts; function serializeCompilerOptions(options) { var result = {}; var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name_32 in options) { - if (ts.hasProperty(options, name_32)) { - var value = options[name_32]; - switch (name_32) { + for (var name_28 in options) { + if (ts.hasProperty(options, name_28)) { + var value = options[name_28]; + switch (name_28) { case "init": case "watch": case "version": @@ -32902,17 +33657,17 @@ var ts; case "project": break; default: - var optionDefinition = optionsNameMap[name_32.toLowerCase()]; + var optionDefinition = optionsNameMap[name_28.toLowerCase()]; if (optionDefinition) { if (typeof optionDefinition.type === "string") { - result[name_32] = value; + result[name_28] = value; } else { var typeMap = optionDefinition.type; for (var key in typeMap) { if (ts.hasProperty(typeMap, key)) { if (typeMap[key] === value) - result[name_32] = key; + result[name_28] = key; } } } diff --git a/lib/tsserver.js b/lib/tsserver.js index 9f0c1674080..b04981dc6db 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -19,7 +19,7 @@ var ts; function OperationCanceledException() { } return OperationCanceledException; - })(); + }()); ts.OperationCanceledException = OperationCanceledException; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -247,9 +247,11 @@ var ts; var count = array.length; if (count > 0) { var pos = 0; - var result = arguments.length <= 2 ? array[pos++] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos++; while (pos < count) { - result = f(result, array[pos++]); + result = f(result, array[pos]); + pos++; } return result; } @@ -261,9 +263,11 @@ var ts; if (array) { var pos = array.length - 1; if (pos >= 0) { - var result = arguments.length <= 2 ? array[pos--] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos--; while (pos >= 0) { - result = f(result, array[pos--]); + result = f(result, array[pos]); + pos--; } return result; } @@ -346,6 +350,22 @@ var ts; 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; + } + ts.isArray = isArray; function memoize(callback) { var value; return function () { @@ -639,7 +659,7 @@ var ts; } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; function getBaseFileName(path) { - if (!path) { + if (path === undefined) { return undefined; } var i = path.lastIndexOf(ts.directorySeparator); @@ -664,14 +684,19 @@ var ts; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; - ts.supportedExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedJsExtensions = ts.supportedExtensions.concat(".js", ".jsx"); - function isSupportedSourceFileName(fileName) { + ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedJavascriptExtensions = [".js", ".jsx"]; + var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + function getSupportedExtensions(options) { + return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + ts.getSupportedExtensions = getSupportedExtensions; + function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; } - for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; + for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -690,22 +715,6 @@ var ts; return path; } ts.removeFileExtension = removeFileExtension; - var backslashOrDoubleQuote = /[\"\\]/g; - var escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { - "\0": "\\0", - "\t": "\\t", - "\v": "\\v", - "\f": "\\f", - "\b": "\\b", - "\r": "\\r", - "\n": "\\n", - "\\": "\\\\", - "\"": "\\\"", - "\u2028": "\\u2028", - "\u2029": "\\u2029", - "\u0085": "\\u0085" - }; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -902,7 +911,6 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); - var _tty = require("tty"); function createWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } if (chunkSize === void 0) { chunkSize = 30; } @@ -970,9 +978,6 @@ var ts; }; } var watchedFileSet = createWatchedFileSet(); - function isNode4OrLater() { - return parseInt(process.version.charAt(1)) >= 4; - } var platform = _os.platform(); var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; function readFile(fileName, encoding) { @@ -1055,9 +1060,6 @@ var ts; readFile: readFile, writeFile: writeFile, watchFile: function (fileName, callback) { - if (isNode4OrLater()) { - return _fs.watch(fileName, function (eventName, relativeFileName) { return callback(fileName); }); - } var watchedFile = watchedFileSet.addFile(fileName, callback); return { close: function () { return watchedFileSet.removeFile(watchedFile); } @@ -1103,12 +1105,40 @@ var ts; } }; } + function getChakraSystem() { + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, encoding) { + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + if (writeByteOrderMark) { + data = "\uFEFF" + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + readDirectory: ChakraHost.readDirectory, + exit: ChakraHost.quit + }; + } if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { return getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { return getNodeSystem(); } + else if (typeof ChakraHost !== "undefined") { + return getChakraSystem(); + } else { return undefined; } @@ -1226,7 +1256,7 @@ var ts; Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: ts.DiagnosticCategory.Error, key: "Modifiers_not_permitted_on_index_signature_members_1145", message: "Modifiers not permitted on index signature members." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_1148", message: "Cannot compile modules unless the '--module' flag is provided." }, + Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_optio_1148", message: "Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -1313,6 +1343,10 @@ var ts; _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, + An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, + A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, + A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, @@ -1326,11 +1360,12 @@ var ts; Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list_2313", message: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." }, + Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, @@ -1340,6 +1375,7 @@ var ts; Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, + Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, @@ -1410,6 +1446,7 @@ var ts; Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, + Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, @@ -1523,6 +1560,8 @@ var ts; Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, + A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_return_type_positions_for_functions_and_methods: { code: 2519, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_r_2519", message: "A 'this'-based type predicate is only allowed within a class or interface's members, get accessors, or return type positions for functions and methods." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, @@ -1532,7 +1571,7 @@ var ts; A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_must_be_an_object_type_2600", message: "JSX element attributes type '{0}' must be an object type." }, + 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." }, Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'" }, @@ -1548,6 +1587,9 @@ var ts; Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element" }, + Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'" }, + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, 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}'." }, @@ -1632,6 +1674,11 @@ var ts; Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, + Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'" }, + The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'" }, + Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalide value for '--reactNamespace'. '{0}' is not a valid identifier." }, 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." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -1642,6 +1689,7 @@ var ts; Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -1697,6 +1745,8 @@ var ts; Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, + Allow_javascript_files_to_be_compiled: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6083", message: "Allow javascript files to be compiled." }, + Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit_6084", message: "Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit" }, 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." }, @@ -1744,7 +1794,8 @@ var ts; Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'" }, An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." } + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, + JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." } }; })(ts || (ts = {})); var ts; @@ -1934,7 +1985,8 @@ var ts; var pos = 0; var lineStart = 0; while (pos < text.length) { - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 13: if (text.charCodeAt(pos) === 10) { @@ -2037,6 +2089,9 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; function skipTrivia(text, pos, stopAfterLineBreak) { + if (!(pos >= 0)) { + return pos; + } while (true) { var ch = text.charCodeAt(pos); switch (ch) { @@ -2254,6 +2309,18 @@ var ts; ch > 127 && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; + function isIdentifier(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1, n = name.length; i < n; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifier = isIdentifier; function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0; } var pos; @@ -2363,7 +2430,8 @@ var ts; return value; } function scanString() { - var quote = text.charCodeAt(pos++); + var quote = text.charCodeAt(pos); + pos++; var result = ""; var start = pos; while (true) { @@ -2450,7 +2518,8 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); return ""; } - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 48: return "\0"; @@ -2659,7 +2728,8 @@ var ts; } return pos += 2, token = 31; } - return pos++, token = 49; + pos++; + return token = 49; case 34: case 39: tokenValue = scanString(); @@ -2670,7 +2740,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 62; } - return pos++, token = 40; + pos++; + return token = 40; case 38: if (text.charCodeAt(pos + 1) === 38) { return pos += 2, token = 51; @@ -2678,11 +2749,14 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 66; } - return pos++, token = 46; + pos++; + return token = 46; case 40: - return pos++, token = 17; + pos++; + return token = 17; case 41: - return pos++, token = 18; + pos++; + return token = 18; case 42: if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 59; @@ -2693,7 +2767,8 @@ var ts; } return pos += 2, token = 38; } - return pos++, token = 37; + pos++; + return token = 37; case 43: if (text.charCodeAt(pos + 1) === 43) { return pos += 2, token = 41; @@ -2701,9 +2776,11 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 57; } - return pos++, token = 35; + pos++; + return token = 35; case 44: - return pos++, token = 24; + pos++; + return token = 24; case 45: if (text.charCodeAt(pos + 1) === 45) { return pos += 2, token = 42; @@ -2711,7 +2788,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 58; } - return pos++, token = 36; + pos++; + return token = 36; case 46: if (isDigit(text.charCodeAt(pos + 1))) { tokenValue = scanNumber(); @@ -2720,7 +2798,8 @@ var ts; if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) { return pos += 3, token = 22; } - return pos++, token = 21; + pos++; + return token = 21; case 47: if (text.charCodeAt(pos + 1) === 47) { pos += 2; @@ -2766,7 +2845,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 61; } - return pos++, token = 39; + pos++; + return token = 39; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; @@ -2814,9 +2894,11 @@ var ts; tokenValue = scanNumber(); return token = 8; case 58: - return pos++, token = 54; + pos++; + return token = 54; case 59: - return pos++, token = 23; + pos++; + return token = 23; case 60: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2841,7 +2923,8 @@ var ts; text.charCodeAt(pos + 2) !== 42) { return pos += 2, token = 26; } - return pos++, token = 25; + pos++; + return token = 25; case 61: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2861,7 +2944,8 @@ var ts; if (text.charCodeAt(pos + 1) === 62) { return pos += 2, token = 34; } - return pos++, token = 56; + pos++; + return token = 56; case 62: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2872,20 +2956,26 @@ var ts; return token = 7; } } - return pos++, token = 27; + pos++; + return token = 27; case 63: - return pos++, token = 53; + pos++; + return token = 53; case 91: - return pos++, token = 19; + pos++; + return token = 19; case 93: - return pos++, token = 20; + pos++; + return token = 20; case 94: if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 68; } - return pos++, token = 48; + pos++; + return token = 48; case 123: - return pos++, token = 15; + pos++; + return token = 15; case 124: if (text.charCodeAt(pos + 1) === 124) { return pos += 2, token = 52; @@ -2893,13 +2983,17 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 67; } - return pos++, token = 47; + pos++; + return token = 47; case 125: - return pos++, token = 16; + pos++; + return token = 16; case 126: - return pos++, token = 50; + pos++; + return token = 50; case 64: - return pos++, token = 55; + pos++; + return token = 55; case 92: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -2908,7 +3002,8 @@ var ts; return token = getIdentifierToken(); } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0; + pos++; + return token = 0; default: if (isIdentifierStart(ch, languageVersion)) { pos++; @@ -2930,7 +3025,8 @@ var ts; continue; } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0; + pos++; + return token = 0; } } } @@ -2946,10 +3042,12 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 64; } - return pos++, token = 44; + pos++; + return token = 44; } if (text.charCodeAt(pos) === 61) { - return pos++, token = 29; + pos++; + return token = 29; } } return token; @@ -3032,7 +3130,7 @@ var ts; break; } } - return token = 236; + return token = 238; } function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { @@ -3152,6 +3250,11 @@ var ts; description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, error: ts.Diagnostics.Argument_for_jsx_must_be_preserve_or_react }, + { + name: "reactNamespace", + type: "string", + description: ts.Diagnostics.Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit + }, { name: "listFiles", type: "boolean" @@ -3376,6 +3479,16 @@ var ts; name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "allowJs", + type: "boolean", + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled } ]; var optionNameMapCache; @@ -3409,7 +3522,8 @@ var ts; function parseStrings(args) { var i = 0; while (i < args.length) { - var s = args[i++]; + var s = args[i]; + i++; if (s.charCodeAt(0) === 64) { parseResponseFile(s.slice(1)); } @@ -3425,17 +3539,20 @@ var ts; } switch (opt.type) { case "number": - options[opt.name] = parseInt(args[i++]); + options[opt.name] = parseInt(args[i]); + i++; break; case "boolean": options[opt.name] = true; break; case "string": - options[opt.name] = args[i++] || ""; + options[opt.name] = args[i] || ""; + i++; break; default: var map_1 = opt.type; - var key = (args[i++] || "").toLowerCase(); + var key = (args[i] || "").toLowerCase(); + i++; if (ts.hasProperty(map_1, key)) { options[opt.name] = map_1[key]; } @@ -3527,8 +3644,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath) { - var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors; + function parseJsonConfigFileContent(json, host, basePath, existingOptions) { + if (existingOptions === void 0) { existingOptions = {}; } + var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), optionsFromJsonConfigFile = _a.options, errors = _a.errors; + var options = ts.extend(existingOptions, optionsFromJsonConfigFile); return { options: options, fileNames: getFileNames(), @@ -3545,23 +3664,26 @@ var ts; } } else { + var filesSeen = {}; var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; - var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); - for (var i = 0; i < sysFiles.length; i++) { - var name_5 = sysFiles[i]; - if (ts.fileExtensionIs(name_5, ".d.ts")) { - var baseName = name_5.substr(0, name_5.length - ".d.ts".length); - if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) { - fileNames.push(name_5); + var supportedExtensions = ts.getSupportedExtensions(options); + ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); + for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; + var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); + for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { + var fileName = filesInDirWithExtension_1[_a]; + if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { + continue; } - } - else if (ts.fileExtensionIs(name_5, ".ts")) { - if (!ts.contains(sysFiles, name_5 + "x")) { - fileNames.push(name_5); + if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { + var baseName = fileName.substr(0, fileName.length - extension.length); + if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { + continue; + } } - } - else { - fileNames.push(name_5); + filesSeen[fileName] = true; + fileNames.push(fileName); } } } @@ -3669,7 +3791,7 @@ var ts; if (array1.length !== array2.length) { return false; } - for (var i = 0; i < array1.length; ++i) { + for (var i = 0; i < array1.length; i++) { var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; if (!equals) { return false; @@ -3709,7 +3831,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 248) { + while (node && node.kind !== 250) { node = node.parent; } return node; @@ -3800,15 +3922,15 @@ var ts; return current; } switch (current.kind) { - case 248: + case 250: + case 222: + case 246: case 220: - case 244: - case 218: - case 199: - case 200: case 201: + case 202: + case 203: return current; - case 192: + case 194: if (!isFunctionLike(current.parent)) { return current; } @@ -3819,9 +3941,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 211 && + declaration.kind === 213 && declaration.parent && - declaration.parent.kind === 244; + declaration.parent.kind === 246; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; function declarationNameToString(name) { @@ -3857,22 +3979,23 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 248: + case 250: var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); if (pos_1 === sourceFile.text.length) { return ts.createTextSpan(0, 0); } return getSpanOfTokenAtPosition(sourceFile, pos_1); - case 211: - case 163: - case 214: - case 186: - case 215: - case 218: - case 217: - case 247: case 213: - case 173: + case 165: + case 216: + case 188: + case 217: + case 220: + case 219: + case 249: + case 215: + case 175: + case 143: errorNode = node.name; break; } @@ -3898,11 +4021,11 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 217 && isConst(node); + return node.kind === 219 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 163 || isBindingPattern(node))) { + while (node && (node.kind === 165 || isBindingPattern(node))) { node = node.parent; } return node; @@ -3910,14 +4033,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 211) { + if (node.kind === 213) { node = node.parent; } - if (node && node.kind === 212) { + if (node && node.kind === 214) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 193) { + if (node && node.kind === 195) { flags |= node.flags; } return flags; @@ -3932,7 +4055,7 @@ var ts; } ts.isLet = isLet; function isPrologueDirective(node) { - return node.kind === 195 && node.expression.kind === 9; + return node.kind === 197 && node.expression.kind === 9; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { @@ -3962,7 +4085,7 @@ var ts; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isTypeNode(node) { - if (151 <= node.kind && node.kind <= 160) { + if (150 <= node.kind && node.kind <= 162) { return true; } switch (node.kind) { @@ -3973,42 +4096,40 @@ var ts; case 131: return true; case 103: - return node.parent.kind !== 177; - case 9: - return node.parent.kind === 138; - case 188: + return node.parent.kind !== 179; + case 190: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); case 69: if (node.parent.kind === 135 && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 166 && node.parent.name === node) { + else if (node.parent.kind === 168 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 69 || node.kind === 135 || node.kind === 166, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + ts.Debug.assert(node.kind === 69 || node.kind === 135 || node.kind === 168, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); case 135: - case 166: + case 168: case 97: var parent_1 = node.parent; if (parent_1.kind === 154) { return false; } - if (151 <= parent_1.kind && parent_1.kind <= 160) { + if (150 <= parent_1.kind && parent_1.kind <= 162) { return true; } switch (parent_1.kind) { - case 188: + case 190: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); case 137: return node === parent_1.constraint; case 141: case 140: case 138: - case 211: - return node === parent_1.type; case 213: - case 173: - case 174: + return node === parent_1.type; + case 215: + case 175: + case 176: case 144: case 143: case 142: @@ -4019,12 +4140,12 @@ var ts; case 148: case 149: return node === parent_1.type; - case 171: + case 173: return node === parent_1.type; - case 168: - case 169: - return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; case 170: + case 171: + return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + case 172: return false; } } @@ -4035,23 +4156,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 204: + case 206: return visitor(node); - case 220: - case 192: - case 196: - case 197: + case 222: + case 194: case 198: case 199: case 200: case 201: - case 205: - case 206: - case 241: - case 242: + case 202: + case 203: case 207: - case 209: + case 208: + case 243: case 244: + case 209: + case 211: + case 246: return ts.forEachChild(node, traverse); } } @@ -4061,24 +4182,24 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 184: + case 186: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } + case 219: case 217: - case 215: + case 220: case 218: case 216: - case 214: - case 186: + case 188: return; default: if (isFunctionLike(node)) { - var name_6 = node.name; - if (name_6 && name_6.kind === 136) { - traverse(name_6.expression); + var name_5 = node.name; + if (name_5 && name_5.kind === 136) { + traverse(name_5.expression); return; } } @@ -4092,14 +4213,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 163: - case 247: + case 165: + case 249: case 138: - case 245: + case 247: case 141: case 140: - case 246: - case 211: + case 248: + case 213: return true; } } @@ -4111,7 +4232,7 @@ var ts; } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 214 || node.kind === 186); + return node && (node.kind === 216 || node.kind === 188); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -4121,9 +4242,9 @@ var ts; function isFunctionLikeKind(kind) { switch (kind) { case 144: - case 173: - case 213: - case 174: + case 175: + case 215: + case 176: case 143: case 142: case 145: @@ -4144,8 +4265,8 @@ var ts; case 144: case 145: case 146: - case 213: - case 173: + case 215: + case 175: return true; } return false; @@ -4153,26 +4274,30 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { + case 201: + case 202: + case 203: case 199: case 200: - case 201: - case 197: - case 198: return true; - case 207: + case 209: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 192 && isFunctionLike(node.parent); + return node && node.kind === 194 && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 143 && node.parent.kind === 165; + return node && node.kind === 143 && node.parent.kind === 167; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; function getContainingFunction(node) { while (true) { node = node.parent; @@ -4212,13 +4337,13 @@ var ts; node = node.parent; } break; - case 174: + case 176: if (!includeArrowFunctions) { continue; } - case 213: - case 173: - case 218: + case 215: + case 175: + case 220: case 141: case 140: case 143: @@ -4229,37 +4354,27 @@ var ts; case 147: case 148: case 149: - case 217: - case 248: + case 219: + case 250: return node; } } } ts.getThisContainer = getThisContainer; - function getSuperContainer(node, includeFunctions) { + function getSuperContainer(node, stopOnFunctions) { while (true) { node = node.parent; - if (!node) + if (!node) { return node; + } switch (node.kind) { case 136: - if (isClassLike(node.parent.parent)) { - return node; - } node = node.parent; break; - case 139: - if (node.parent.kind === 138 && isClassElement(node.parent.parent)) { - node = node.parent.parent; - } - else if (isClassElement(node.parent)) { - node = node.parent; - } - break; - case 213: - case 173: - case 174: - if (!includeFunctions) { + case 215: + case 175: + case 176: + if (!stopOnFunctions) { continue; } case 141: @@ -4270,6 +4385,14 @@ var ts; case 145: case 146: return node; + case 139: + if (node.parent.kind === 138 && isClassElement(node.parent.parent)) { + node = node.parent.parent; + } + else if (isClassElement(node.parent)) { + node = node.parent; + } + break; } } } @@ -4279,7 +4402,7 @@ var ts; switch (node.kind) { case 151: return node.typeName; - case 188: + case 190: return node.expression; case 69: case 135: @@ -4290,7 +4413,7 @@ var ts; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 170) { + if (node.kind === 172) { return node.tag; } return node.expression; @@ -4298,23 +4421,23 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 214: + case 216: return true; case 141: - return node.parent.kind === 214; + return node.parent.kind === 216; case 138: - return node.parent.body && node.parent.parent.kind === 214; + return node.parent.body && node.parent.parent.kind === 216; case 145: case 146: case 143: - return node.body && node.parent.kind === 214; + return node.body && node.parent.kind === 216; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { switch (node.kind) { - case 214: + case 216: if (node.decorators) { return true; } @@ -4340,27 +4463,12 @@ var ts; return false; } ts.nodeIsDecorated = nodeIsDecorated; - function childIsDecorated(node) { - switch (node.kind) { - case 214: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 143: - case 146: - return ts.forEach(node.parameters, nodeIsDecorated); - } - return false; - } - ts.childIsDecorated = childIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); - } - ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function isPropertyAccessExpression(node) { - return node.kind === 166; + return node.kind === 168; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 167; + return node.kind === 169; } ts.isElementAccessExpression = isElementAccessExpression; function isExpression(node) { @@ -4370,34 +4478,34 @@ var ts; case 99: case 84: case 10: - case 164: - case 165: case 166: case 167: case 168: case 169: case 170: - case 189: case 171: case 172: + case 191: case 173: - case 186: case 174: - case 177: case 175: + case 188: case 176: case 179: - case 180: + case 177: + case 178: case 181: case 182: - case 185: case 183: - case 11: - case 187: - case 233: - case 234: case 184: - case 178: + case 187: + case 185: + case 11: + case 189: + case 235: + case 236: + case 186: + case 180: return true; case 135: while (node.parent.kind === 135) { @@ -4413,47 +4521,47 @@ var ts; case 97: var parent_2 = node.parent; switch (parent_2.kind) { - case 211: + case 213: case 138: case 141: case 140: + case 249: case 247: - case 245: - case 163: + case 165: return parent_2.initializer === node; - case 195: - case 196: case 197: case 198: - case 204: - case 205: - case 206: - case 241: - case 208: - case 206: - return parent_2.expression === node; case 199: + case 200: + case 206: + case 207: + case 208: + case 243: + case 210: + case 208: + return parent_2.expression === node; + case 201: var forStatement = parent_2; - return (forStatement.initializer === node && forStatement.initializer.kind !== 212) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 214) || forStatement.condition === node || forStatement.incrementor === node; - case 200: - case 201: + case 202: + case 203: var forInStatement = parent_2; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 212) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 214) || forInStatement.expression === node; - case 171: - case 189: + case 173: + case 191: return node === parent_2.expression; - case 190: + case 192: return node === parent_2.expression; case 136: return node === parent_2.expression; case 139: - case 240: - case 239: + case 242: + case 241: return true; - case 188: + case 190: return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: if (isExpression(parent_2)) { @@ -4475,7 +4583,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 && node.moduleReference.kind === 232; + return node.kind === 223 && node.moduleReference.kind === 234; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -4484,7 +4592,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 && node.moduleReference.kind !== 232; + return node.kind === 223 && node.moduleReference.kind !== 234; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -4496,43 +4604,54 @@ var ts; } ts.isInJavaScriptFile = isInJavaScriptFile; function isRequireCall(expression) { - return expression.kind === 168 && + return expression.kind === 170 && expression.expression.kind === 69 && expression.expression.text === "require" && expression.arguments.length === 1 && expression.arguments[0].kind === 9; } ts.isRequireCall = isRequireCall; - function isExportsPropertyAssignment(expression) { - return isInJavaScriptFile(expression) && - (expression.kind === 181) && - (expression.operatorToken.kind === 56) && - (expression.left.kind === 166) && - (expression.left.expression.kind === 69) && - ((expression.left.expression).text === "exports"); + function getSpecialPropertyAssignmentKind(expression) { + if (expression.kind !== 183) { + return 0; + } + var expr = expression; + if (expr.operatorToken.kind !== 56 || expr.left.kind !== 168) { + return 0; + } + var lhs = expr.left; + if (lhs.expression.kind === 69) { + var lhsId = lhs.expression; + if (lhsId.text === "exports") { + return 1; + } + else if (lhsId.text === "module" && lhs.name.text === "exports") { + return 2; + } + } + else if (lhs.expression.kind === 97) { + return 4; + } + else if (lhs.expression.kind === 168) { + var innerPropertyAccess = lhs.expression; + if (innerPropertyAccess.expression.kind === 69 && innerPropertyAccess.name.text === "prototype") { + return 3; + } + } + return 0; } - ts.isExportsPropertyAssignment = isExportsPropertyAssignment; - function isModuleExportsAssignment(expression) { - return isInJavaScriptFile(expression) && - (expression.kind === 181) && - (expression.operatorToken.kind === 56) && - (expression.left.kind === 166) && - (expression.left.expression.kind === 69) && - ((expression.left.expression).text === "module") && - (expression.left.name.text === "exports"); - } - ts.isModuleExportsAssignment = isModuleExportsAssignment; + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 222) { + if (node.kind === 224) { return node.moduleSpecifier; } - if (node.kind === 221) { + if (node.kind === 223) { var reference = node.moduleReference; - if (reference.kind === 232) { + if (reference.kind === 234) { return reference.expression; } } - if (node.kind === 228) { + if (node.kind === 230) { return node.moduleSpecifier; } } @@ -4543,8 +4662,8 @@ var ts; case 138: case 143: case 142: - case 246: - case 245: + case 248: + case 247: case 141: case 140: return node.questionToken !== undefined; @@ -4554,9 +4673,9 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 261 && + return node.kind === 263 && node.parameters.length > 0 && - node.parameters[0].type.kind === 263; + node.parameters[0].type.kind === 265; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function getJSDocTag(node, kind) { @@ -4570,15 +4689,15 @@ var ts; } } function getJSDocTypeTag(node) { - return getJSDocTag(node, 269); + return getJSDocTag(node, 271); } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 268); + return getJSDocTag(node, 270); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 270); + return getJSDocTag(node, 272); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getCorrespondingJSDocParameterTag(parameter) { @@ -4587,10 +4706,10 @@ var ts; var docComment = parameter.parent.jsDocComment; if (docComment) { return ts.forEach(docComment.tags, function (t) { - if (t.kind === 267) { + if (t.kind === 269) { var parameterTag = t; - var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_7.text === parameterName) { + var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_6.text === parameterName) { return t; } } @@ -4606,12 +4725,12 @@ var ts; function isRestParameter(node) { if (node) { if (node.parserContextFlags & 32) { - if (node.type && node.type.kind === 262) { + if (node.type && node.type.kind === 264) { return true; } var paramTag = getCorrespondingJSDocParameterTag(node); if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 262; + return paramTag.typeExpression.type.kind === 264; } } return node.dotDotDotToken !== undefined; @@ -4632,7 +4751,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 162 || node.kind === 161); + return !!node && (node.kind === 164 || node.kind === 163); } ts.isBindingPattern = isBindingPattern; function isNodeDescendentOf(node, ancestor) { @@ -4656,34 +4775,34 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 174: - case 163: - case 214: - case 186: + case 176: + case 165: + case 216: + case 188: case 144: - case 217: - case 247: - case 230: - case 213: - case 173: - case 145: - case 223: - case 221: - case 226: + case 219: + case 249: + case 232: case 215: + case 175: + case 145: + case 225: + case 223: + case 228: + case 217: case 143: case 142: - case 218: - case 224: + case 220: + case 226: case 138: - case 245: + case 247: case 141: case 140: case 146: - case 246: - case 216: + case 248: + case 218: case 137: - case 211: + case 213: return true; } return false; @@ -4691,25 +4810,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 203: - case 202: - case 210: - case 197: - case 195: - case 194: - case 200: - case 201: - case 199: - case 196: - case 207: + case 205: case 204: + case 212: + case 199: + case 197: + case 196: + case 202: + case 203: + case 201: + case 198: + case 209: case 206: case 208: - case 209: - case 193: - case 198: - case 205: - case 227: + case 210: + case 211: + case 195: + case 200: + case 207: + case 229: return true; default: return false; @@ -4736,7 +4855,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 226 || parent.kind === 230) { + if (parent.kind === 228 || parent.kind === 232) { if (parent.propertyName) { return true; } @@ -4756,9 +4875,9 @@ var ts; case 142: case 145: case 146: + case 249: case 247: - case 245: - case 166: + case 168: return parent.name === node; case 135: if (parent.right === node) { @@ -4768,22 +4887,22 @@ var ts; return parent.kind === 154; } return false; - case 163: - case 226: + case 165: + case 228: return parent.propertyName === node; - case 230: + case 232: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 221 || - node.kind === 223 && !!node.name || - node.kind === 224 || + return node.kind === 223 || + node.kind === 225 && !!node.name || node.kind === 226 || - node.kind === 230 || - node.kind === 227 && node.expression.kind === 69; + node.kind === 228 || + node.kind === 232 || + node.kind === 229 && node.expression.kind === 69; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -4916,7 +5035,7 @@ var ts; return node.kind === 69 && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; - function isModifier(token) { + function isModifierKind(token) { switch (token) { case 115: case 118: @@ -4932,39 +5051,56 @@ var ts; } return false; } - ts.isModifier = isModifier; + ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); return root.kind === 138; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 163) { + while (node.kind === 165) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 218 || n.kind === 248; + return isFunctionLike(n) || n.kind === 220 || n.kind === 250; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function cloneEntityName(node) { - if (node.kind === 69) { - var clone_1 = createSynthesizedNode(69); - clone_1.text = node.text; - return clone_1; + function cloneNode(node, location, flags, parent) { + var clone = location !== undefined + ? ts.createNode(node.kind, location.pos, location.end) + : createSynthesizedNode(node.kind); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; } - else { - var clone_2 = createSynthesizedNode(135); - clone_2.left = cloneEntityName(node.left); - clone_2.left.parent = clone_2; - clone_2.right = cloneEntityName(node.right); - clone_2.right.parent = clone_2; - return clone_2; + if (flags !== undefined) { + clone.flags = flags; } + if (parent !== undefined) { + clone.parent = parent; + } + return clone; + } + ts.cloneNode = cloneNode; + function cloneEntityName(node, parent) { + var clone = cloneNode(node, node, node.flags, parent); + if (isQualifiedName(clone)) { + var left = clone.left, right = clone.right; + clone.left = cloneEntityName(left, clone); + clone.right = cloneNode(right, right, right.flags, parent); + } + return clone; } ts.cloneEntityName = cloneEntityName; + function isQualifiedName(node) { + return node.kind === 135; + } + ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { return node.pos === -1; } @@ -5167,8 +5303,8 @@ var ts; writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, - increaseIndent: function () { return indent++; }, - decreaseIndent: function () { return indent--; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, getIndent: function () { return indent; }, getTextPos: function () { return output.length; }, getLine: function () { return lineCount + 1; }, @@ -5179,8 +5315,10 @@ var ts; } ts.createTextWriter = createTextWriter; function getExternalModuleNameFromPath(host, fileName) { - var dir = host.getCurrentDirectory(); - var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, fileName, dir, function (f) { return host.getCanonicalFileName(f); }, false); + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); return ts.removeFileExtension(relativePath); } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; @@ -5196,6 +5334,61 @@ var ts; return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return compilerOptions.module ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? 5 : 0; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + onBundledEmit(host); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + if (!isDeclarationFile(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, sourceFile.languageVariant === 1 && options.jsx === 1 ? ".jsx" : ".js"); + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitFilePath(jsFilePath, options) : undefined + }; + action(emitFileNames, [sourceFile], false); + } + function onBundledEmit(host) { + var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + (!isExternalModule(sourceFile) || + (getEmitModuleKind(options) && isExternalModule(sourceFile))); }); + if (bundledSources.length) { + var jsFilePath = options.outFile || options.out; + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: getDeclarationEmitFilePath(jsFilePath, options) + }; + action(emitFileNames, bundledSources, true); + } + } + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getDeclarationEmitFilePath(jsFilePath, options) { + return options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + } + } + ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); @@ -5204,7 +5397,7 @@ var ts; ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { - diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); }); } ts.writeFile = writeFile; @@ -5228,16 +5421,6 @@ var ts; return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; - function shouldEmitToOwnFile(sourceFile, compilerOptions) { - if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !(compilerOptions.outFile || compilerOptions.out))) { - return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); - } - return false; - } - return false; - } - ts.shouldEmitToOwnFile = shouldEmitToOwnFile; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -5437,24 +5620,24 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 166: - case 167: - case 169: case 168: - case 233: - case 234: + case 169: + case 171: case 170: - case 164: + case 235: + case 236: case 172: - case 165: - case 186: - case 173: + case 166: + case 174: + case 167: + case 188: + case 175: case 69: case 10: case 8: case 9: case 11: - case 183: + case 185: case 84: case 93: case 97: @@ -5471,7 +5654,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 188 && + return node.kind === 190 && node.parent.token === 83 && isClassLike(node.parent.parent); } @@ -5493,15 +5676,15 @@ var ts; } function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 135 && node.parent.right === node) || - (node.parent.kind === 166 && node.parent.name === node); + (node.parent.kind === 168 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 165) { + if (kind === 167) { return expression.properties.length === 0; } - if (kind === 164) { + if (kind === 166) { return expression.elements.length === 0; } return false; @@ -5512,13 +5695,9 @@ var ts; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function hasJavaScriptFileExtension(fileName) { - return ts.fileExtensionIs(fileName, ".js") || ts.fileExtensionIs(fileName, ".jsx"); + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function allowsJsxExpressions(fileName) { - return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx"); - } - ts.allowsJsxExpressions = allowsJsxExpressions; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -5548,6 +5727,39 @@ var ts; } return output; } + ts.stringify = typeof JSON !== "undefined" && JSON.stringify + ? JSON.stringify + : stringifyFallback; + function stringifyFallback(value) { + return value === undefined ? undefined : stringifyValue(value); + } + function stringifyValue(value) { + return typeof value === "string" ? "\"" + escapeString(value) + "\"" + : typeof value === "number" ? isFinite(value) ? String(value) : "null" + : typeof value === "boolean" ? value ? "true" : "false" + : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) + : "null"; + } + function cycleCheck(cb, value) { + ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); + value.__cycle = true; + var result = cb(value); + delete value.__cycle; + return result; + } + function stringifyArray(value) { + return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; + } + function stringifyElement(memo, value) { + return (memo ? memo + "," : memo) + stringifyValue(value); + } + function stringifyObject(value) { + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + } + function stringifyProperty(memo, value, key) { + return value === undefined || typeof value === "function" || key === "__cycle" ? memo + : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); + } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; function convertToBase64(input) { var result = ""; @@ -5718,13 +5930,17 @@ var ts; function getTypeParameterOwner(d) { if (d && d.kind === 137) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 215) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 217) { return current; } } } } ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return node.flags & 56 && node.parent.kind === 144 && ts.isClassLike(node.parent.parent); + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; })(ts || (ts = {})); var ts; (function (ts) { @@ -5732,7 +5948,7 @@ var ts; var NodeConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 248) { + if (kind === 250) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else { @@ -5775,7 +5991,7 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 246: + case 248: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -5785,9 +6001,9 @@ var ts; case 138: case 141: case 140: - case 245: - case 211: - case 163: + case 247: + case 213: + case 165: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -5811,9 +6027,9 @@ var ts; case 144: case 145: case 146: - case 173: - case 213: - case 174: + case 175: + case 215: + case 176: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -5843,271 +6059,271 @@ var ts; return visitNodes(cbNodes, node.types); case 160: return visitNode(cbNode, node.type); - case 161: - case 162: - return visitNodes(cbNodes, node.elements); + case 163: case 164: return visitNodes(cbNodes, node.elements); - case 165: - return visitNodes(cbNodes, node.properties); case 166: + return visitNodes(cbNodes, node.elements); + case 167: + return visitNodes(cbNodes, node.properties); + case 168: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 167: + case 169: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 168: - case 169: + case 170: + case 171: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 170: + case 172: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 171: + case 173: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 172: - return visitNode(cbNode, node.expression); - case 175: - return visitNode(cbNode, node.expression); - case 176: + case 174: return visitNode(cbNode, node.expression); case 177: return visitNode(cbNode, node.expression); - case 179: - return visitNode(cbNode, node.operand); - case 184: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); case 178: return visitNode(cbNode, node.expression); - case 180: - return visitNode(cbNode, node.operand); + case 179: + return visitNode(cbNode, node.expression); case 181: + return visitNode(cbNode, node.operand); + case 186: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 180: + return visitNode(cbNode, node.expression); + case 182: + return visitNode(cbNode, node.operand); + case 183: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 189: + case 191: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 182: + case 184: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 185: + case 187: return visitNode(cbNode, node.expression); - case 192: - case 219: + case 194: + case 221: return visitNodes(cbNodes, node.statements); - case 248: + case 250: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 193: + case 195: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 212: + case 214: return visitNodes(cbNodes, node.declarations); - case 195: + case 197: return visitNode(cbNode, node.expression); - case 196: + case 198: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 197: + case 199: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 198: + case 200: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 199: + case 201: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 200: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 201: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); case 202: - case 203: - return visitNode(cbNode, node.label); - case 204: - return visitNode(cbNode, node.expression); - case 205: - return visitNode(cbNode, node.expression) || + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); + case 203: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 204: + case 205: + return visitNode(cbNode, node.label); case 206: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 220: - return visitNodes(cbNodes, node.clauses); - case 241: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.statements); - case 242: - return visitNodes(cbNodes, node.statements); + return visitNode(cbNode, node.expression); case 207: - return visitNode(cbNode, node.label) || + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); case 208: - return visitNode(cbNode, node.expression); + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 222: + return visitNodes(cbNodes, node.clauses); + case 243: + return visitNode(cbNode, node.expression) || + visitNodes(cbNodes, node.statements); + case 244: + return visitNodes(cbNodes, node.statements); case 209: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 210: + return visitNode(cbNode, node.expression); + case 211: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 244: + case 246: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); case 139: return visitNode(cbNode, node.expression); - case 214: - case 186: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 215: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); case 216: + case 188: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || - visitNode(cbNode, node.type); + visitNodes(cbNodes, node.heritageClauses) || + visitNodes(cbNodes, node.members); case 217: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeParameters) || + visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 247: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); case 218: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 219: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.members); + case 249: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 220: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 221: + case 223: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 222: + case 224: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 223: + case 225: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 224: + case 226: return visitNode(cbNode, node.name); - case 225: - case 229: + case 227: + case 231: return visitNodes(cbNodes, node.elements); - case 228: + case 230: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 226: - case 230: + case 228: + case 232: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 227: + case 229: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 183: + case 185: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 190: + case 192: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); case 136: return visitNode(cbNode, node.expression); - case 243: + case 245: return visitNodes(cbNodes, node.types); - case 188: + case 190: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 232: + case 234: return visitNode(cbNode, node.expression); - case 231: - return visitNodes(cbNodes, node.decorators); case 233: + return visitNodes(cbNodes, node.decorators); + case 235: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 234: - case 235: + case 236: + case 237: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 238: + case 240: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); + case 241: + return visitNode(cbNode, node.expression); + case 242: + return visitNode(cbNode, node.expression); case 239: - return visitNode(cbNode, node.expression); - case 240: - return visitNode(cbNode, node.expression); - case 237: return visitNode(cbNode, node.tagName); - case 249: - return visitNode(cbNode, node.type); - case 253: - return visitNodes(cbNodes, node.types); - case 254: - return visitNodes(cbNodes, node.types); - case 252: - return visitNode(cbNode, node.elementType); - case 256: + case 251: return visitNode(cbNode, node.type); case 255: + return visitNodes(cbNodes, node.types); + case 256: + return visitNodes(cbNodes, node.types); + case 254: + return visitNode(cbNode, node.elementType); + case 258: return visitNode(cbNode, node.type); case 257: - return visitNodes(cbNodes, node.members); + return visitNode(cbNode, node.type); case 259: + return visitNodes(cbNodes, node.members); + case 261: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); - case 260: - return visitNode(cbNode, node.type); - case 261: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); case 262: return visitNode(cbNode, node.type); case 263: - return visitNode(cbNode, node.type); + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); case 264: return visitNode(cbNode, node.type); - case 258: + case 265: + return visitNode(cbNode, node.type); + case 266: + return visitNode(cbNode, node.type); + case 260: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 265: - return visitNodes(cbNodes, node.tags); case 267: + return visitNodes(cbNodes, node.tags); + case 269: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 268: - return visitNode(cbNode, node.typeExpression); - case 269: - return visitNode(cbNode, node.typeExpression); case 270: + return visitNode(cbNode, node.typeExpression); + case 271: + return visitNode(cbNode, node.typeExpression); + case 272: return visitNodes(cbNodes, node.typeParameters); } } @@ -6157,6 +6373,9 @@ var ts; return result; } Parser.parseSourceFile = parseSourceFile; + function getLanguageVariant(fileName) { + return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx") ? 1 : 0; + } function initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); @@ -6172,7 +6391,7 @@ var ts; scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(ts.allowsJsxExpressions(fileName) ? 1 : 0); + scanner.setLanguageVariant(getLanguageVariant(fileName)); } function clearState() { scanner.setText(""); @@ -6211,8 +6430,8 @@ var ts; return; function visit(node) { switch (node.kind) { - case 193: - case 213: + case 195: + case 215: case 138: addJSDocComment(node); } @@ -6247,14 +6466,14 @@ var ts; } Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion) { - var sourceFile = new SourceFileConstructor(248, 0, sourceText.length); + var sourceFile = new SourceFileConstructor(250, 0, sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 : 0; - sourceFile.languageVariant = ts.allowsJsxExpressions(sourceFile.fileName) ? 1 : 0; + sourceFile.languageVariant = getLanguageVariant(sourceFile.fileName); return sourceFile; } function setContextFlag(val, flag) { @@ -6306,9 +6525,6 @@ var ts; function doInYieldContext(func) { return doInsideOfContext(2, func); } - function doOutsideOfYieldContext(func) { - return doOutsideOfContext(2, func); - } function doInDecoratorContext(func) { return doInsideOfContext(4, func); } @@ -6321,9 +6537,6 @@ var ts; function doInYieldAndAwaitContext(func) { return doInsideOfContext(2 | 8, func); } - function doOutsideOfYieldAndAwaitContext(func) { - return doOutsideOfContext(2 | 8, func); - } function inContext(flags) { return (contextFlags & flags) !== 0; } @@ -6364,9 +6577,6 @@ var ts; function nextToken() { return token = scanner.scan(); } - function getTokenPos(pos) { - return ts.skipTrivia(sourceText, pos); - } function reScanGreaterToken() { return token = scanner.reScanGreaterToken(); } @@ -6556,6 +6766,13 @@ var ts; function parseContextualModifier(t) { return token === t && tryParse(nextTokenCanFollowModifier); } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } function nextTokenCanFollowModifier() { if (token === 74) { return nextToken() === 81; @@ -6574,14 +6791,10 @@ var ts; nextToken(); return canFollowModifier(); } - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); + return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifier(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { return token === 19 @@ -6848,7 +7061,7 @@ var ts; case 145: case 146: case 141: - case 191: + case 193: return true; case 143: var methodDeclaration = node; @@ -6862,8 +7075,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 241: - case 242: + case 243: + case 244: return true; } } @@ -6872,42 +7085,42 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 213: - case 193: - case 192: - case 196: + case 215: case 195: - case 208: - case 204: - case 206: - case 203: - case 202: - case 200: - case 201: - case 199: - case 198: - case 205: case 194: - case 209: - case 207: + case 198: case 197: case 210: - case 222: - case 221: - case 228: - case 227: - case 218: - case 214: - case 215: - case 217: + case 206: + case 208: + case 205: + case 204: + case 202: + case 203: + case 201: + case 200: + case 207: + case 196: + case 211: + case 209: + case 199: + case 212: + case 224: + case 223: + case 230: + case 229: + case 220: case 216: + case 217: + case 219: + case 218: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 247; + return node.kind === 249; } function isReusableTypeMember(node) { if (node) { @@ -6923,7 +7136,7 @@ var ts; return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 211) { + if (node.kind !== 213) { return false; } var variableDeclarator = node; @@ -7047,8 +7260,8 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(183); - template.head = parseLiteralNode(); + var template = createNode(185); + template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); var templateSpans = []; templateSpans.pos = getNodePos(); @@ -7060,12 +7273,12 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(190); + var span = createNode(192); span.expression = allowInAnd(parseExpression); var literal; if (token === 16) { reScanTemplateToken(); - literal = parseLiteralNode(); + literal = parseTemplateLiteralFragment(); } else { literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); @@ -7073,8 +7286,17 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(162, true); + } function parseLiteralNode(internName) { - var node = createNode(token); + return parseLiteralLikeNode(token, internName); + } + function parseTemplateLiteralFragment() { + return parseLiteralLikeNode(token, false); + } + function parseLiteralLikeNode(kind, internName) { + var node = createNode(kind); var text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -7096,11 +7318,7 @@ var ts; function parseTypeReferenceOrTypePredicate() { var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); if (typeName.kind === 69 && token === 124 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var node_1 = createNode(150, typeName.pos); - node_1.parameterName = typeName; - node_1.type = parseType(); - return finishNode(node_1); + return parseTypePredicate(typeName); } var node = createNode(151, typeName.pos); node.typeName = typeName; @@ -7109,6 +7327,18 @@ var ts; } return finishNode(node); } + function parseTypePredicate(lhs) { + nextToken(); + var node = createNode(150, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(161); + nextToken(); + return finishNode(node); + } function parseTypeQuery() { var node = createNode(154); parseExpected(101); @@ -7140,7 +7370,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 || isIdentifierOrPattern() || ts.isModifier(token) || token === 55; + return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55; } function setModifiers(node, modifiers) { if (modifiers) { @@ -7154,7 +7384,7 @@ var ts; setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifier(token)) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { nextToken(); } node.questionToken = parseOptionalToken(53); @@ -7222,7 +7452,7 @@ var ts; if (token === 22 || token === 20) { return true; } - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -7269,6 +7499,9 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); + if (token === 56) { + property.initializer = parseNonParameterInitializer(); + } parseTypeMemberSemicolon(); return finishNode(property); } @@ -7280,7 +7513,7 @@ var ts; case 19: return true; default: - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { var result = lookAhead(isStartOfIndexSignatureDeclaration); if (result) { return result; @@ -7290,7 +7523,7 @@ var ts; } } function isStartOfIndexSignatureDeclaration() { - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { nextToken(); } return isIndexSignature(); @@ -7320,7 +7553,7 @@ var ts; case 8: return parsePropertyOrMethodSignature(); default: - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { var result = tryParse(parseIndexSignatureWithModifiers); if (result) { return result; @@ -7393,10 +7626,18 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReferenceOrTypePredicate(); case 9: - return parseLiteralNode(true); + return parseStringLiteralTypeNode(); case 103: - case 97: return parseTokenNode(); + case 97: { + var thisKeyword = parseThisTypeNode(); + if (token === 124 && !scanner.hasPrecedingLineBreak()) { + return parseTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } case 101: return parseTypeQuery(); case 15: @@ -7477,11 +7718,11 @@ var ts; if (token === 18 || token === 22) { return true; } - if (isIdentifier() || ts.isModifier(token)) { + if (isIdentifier() || ts.isModifierKind(token)) { nextToken(); if (token === 54 || token === 24 || token === 53 || token === 56 || - isIdentifier() || ts.isModifier(token)) { + isIdentifier() || ts.isModifierKind(token)) { return true; } if (token === 18) { @@ -7565,9 +7806,6 @@ var ts; token !== 55 && isStartOfExpression(); } - function allowInAndParseExpression() { - return allowInAnd(parseExpression); - } function parseExpression() { var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { @@ -7623,7 +7861,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(184); + var node = createNode(186); nextToken(); if (!scanner.hasPrecedingLineBreak() && (token === 37 || isStartOfExpression())) { @@ -7637,7 +7875,7 @@ var ts; } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(174, identifier.pos); + var node = createNode(176, identifier.pos); var parameter = createNode(138, identifier.pos); parameter.name = identifier; finishNode(parameter); @@ -7749,7 +7987,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(174); + var node = createNode(176); setModifiers(node, parseModifiersForArrowFunction()); var isAsync = !!(node.flags & 256); fillSignature(54, false, isAsync, !allowAmbiguity, node); @@ -7781,7 +8019,7 @@ var ts; if (!questionToken) { return leftOperand; } - var node = createNode(182, leftOperand.pos); + var node = createNode(184, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -7872,39 +8110,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(181, left.pos); + var node = createNode(183, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(189, left.pos); + var node = createNode(191, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(179); + var node = createNode(181); node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(175); + var node = createNode(177); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(176); + var node = createNode(178); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(177); + var node = createNode(179); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -7919,7 +8157,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(178); + var node = createNode(180); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -7938,7 +8176,7 @@ var ts; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === 38) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 171) { + if (simpleUnaryExpression.kind === 173) { 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); } else { @@ -7986,7 +8224,7 @@ var ts; } function parseIncrementExpression() { if (token === 41 || token === 42) { - var node = createNode(179); + var node = createNode(181); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -7998,7 +8236,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 41 || token === 42) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(180, expression.pos); + var node = createNode(182, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -8021,31 +8259,44 @@ var ts; if (token === 17 || token === 21 || token === 19) { return expression; } - var node = createNode(166, expression.pos); + var node = createNode(168, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 69) { + return lhs.text === rhs.text; + } + return lhs.right.text === rhs.right.text && + tagNamesAreEquivalent(lhs.left, rhs.left); + } function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 235) { - var node = createNode(233, opening.pos); + if (opening.kind === 237) { + var node = createNode(235, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 234); + ts.Debug.assert(opening.kind === 236); result = opening; } if (inExpressionContext && token === 25) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(181, result.pos); + var badNode = createNode(183, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -8057,13 +8308,13 @@ var ts; return result; } function parseJsxText() { - var node = createNode(236, scanner.getStartPos()); + var node = createNode(238, scanner.getStartPos()); token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token) { - case 236: + case 238: return parseJsxText(); case 15: return parseJsxExpression(false); @@ -8083,7 +8334,7 @@ var ts; break; } else if (token === 1) { - parseErrorAtCurrentToken(ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } result.push(parseJsxChild()); @@ -8099,7 +8350,7 @@ var ts; var attributes = parseList(13, parseJsxAttribute); var node; if (token === 27) { - node = createNode(235, fullStart); + node = createNode(237, fullStart); scanJsxText(); } else { @@ -8111,7 +8362,7 @@ var ts; parseExpected(27, undefined, false); scanJsxText(); } - node = createNode(234, fullStart); + node = createNode(236, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -8130,10 +8381,10 @@ var ts; return elementName; } function parseJsxExpression(inExpressionContext) { - var node = createNode(240); + var node = createNode(242); parseExpected(15); if (token !== 16) { - node.expression = parseExpression(); + node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { parseExpected(16); @@ -8149,7 +8400,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(238); + var node = createNode(240); node.name = parseIdentifierName(); if (parseOptional(56)) { switch (token) { @@ -8164,7 +8415,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(239); + var node = createNode(241); parseExpected(15); parseExpected(22); node.expression = parseExpression(); @@ -8172,7 +8423,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(237); + var node = createNode(239); parseExpected(26); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -8185,7 +8436,7 @@ var ts; return finishNode(node); } function parseTypeAssertion() { - var node = createNode(171); + var node = createNode(173); parseExpected(25); node.type = parseType(); parseExpected(27); @@ -8196,7 +8447,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(21); if (dotToken) { - var propertyAccess = createNode(166, expression.pos); + var propertyAccess = createNode(168, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); @@ -8204,7 +8455,7 @@ var ts; continue; } if (!inDecoratorContext() && parseOptional(19)) { - var indexedAccess = createNode(167, expression.pos); + var indexedAccess = createNode(169, expression.pos); indexedAccess.expression = expression; if (token !== 20) { indexedAccess.argumentExpression = allowInAnd(parseExpression); @@ -8218,7 +8469,7 @@ var ts; continue; } if (token === 11 || token === 12) { - var tagExpression = createNode(170, expression.pos); + var tagExpression = createNode(172, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 11 ? parseLiteralNode() @@ -8237,7 +8488,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(168, expression.pos); + var callExpr = createNode(170, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -8245,7 +8496,7 @@ var ts; continue; } else if (token === 17) { - var callExpr = createNode(168, expression.pos); + var callExpr = createNode(170, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -8340,28 +8591,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(172); + var node = createNode(174); parseExpected(17); node.expression = allowInAnd(parseExpression); parseExpected(18); return finishNode(node); } function parseSpreadElement() { - var node = createNode(185); + var node = createNode(187); parseExpected(22); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 22 ? parseSpreadElement() : - token === 24 ? createNode(187) : + token === 24 ? createNode(189) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(164); + var node = createNode(166); parseExpected(19); if (scanner.hasPrecedingLineBreak()) node.flags |= 1024; @@ -8388,7 +8639,6 @@ var ts; } var asteriskToken = parseOptionalToken(37); var tokenIsIdentifier = isIdentifier(); - var nameToken = token; var propertyName = parsePropertyName(); var questionToken = parseOptionalToken(53); if (asteriskToken || token === 17 || token === 25) { @@ -8396,7 +8646,7 @@ var ts; } var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 || token === 16 || token === 56); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(246, fullStart); + var shorthandDeclaration = createNode(248, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; var equalsToken = parseOptionalToken(56); @@ -8407,7 +8657,8 @@ var ts; return finishNode(shorthandDeclaration); } else { - var propertyAssignment = createNode(245, fullStart); + var propertyAssignment = createNode(247, fullStart); + propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(54); @@ -8416,7 +8667,7 @@ var ts; } } function parseObjectLiteralExpression() { - var node = createNode(165); + var node = createNode(167); parseExpected(15); if (scanner.hasPrecedingLineBreak()) { node.flags |= 1024; @@ -8430,7 +8681,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(173); + var node = createNode(175); setModifiers(node, parseModifiers()); parseExpected(87); node.asteriskToken = parseOptionalToken(37); @@ -8452,7 +8703,7 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(169); + var node = createNode(171); parseExpected(92); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -8462,7 +8713,7 @@ var ts; return finishNode(node); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(192); + var node = createNode(194); if (parseExpected(15, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(1, parseStatement); parseExpected(16); @@ -8490,12 +8741,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(194); + var node = createNode(196); parseExpected(23); return finishNode(node); } function parseIfStatement() { - var node = createNode(196); + var node = createNode(198); parseExpected(88); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -8505,7 +8756,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(197); + var node = createNode(199); parseExpected(79); node.statement = parseStatement(); parseExpected(104); @@ -8516,7 +8767,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(198); + var node = createNode(200); parseExpected(104); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -8539,21 +8790,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(90)) { - var forInStatement = createNode(200, pos); + var forInStatement = createNode(202, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(18); forOrForInOrForOfStatement = forInStatement; } else if (parseOptional(134)) { - var forOfStatement = createNode(201, pos); + var forOfStatement = createNode(203, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(18); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(199, pos); + var forStatement = createNode(201, pos); forStatement.initializer = initializer; parseExpected(23); if (token !== 23 && token !== 18) { @@ -8571,7 +8822,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 203 ? 70 : 75); + parseExpected(kind === 205 ? 70 : 75); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -8579,7 +8830,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(204); + var node = createNode(206); parseExpected(94); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -8588,7 +8839,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(205); + var node = createNode(207); parseExpected(105); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -8597,7 +8848,7 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(241); + var node = createNode(243); parseExpected(71); node.expression = allowInAnd(parseExpression); parseExpected(54); @@ -8605,7 +8856,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(242); + var node = createNode(244); parseExpected(77); parseExpected(54); node.statements = parseList(3, parseStatement); @@ -8615,12 +8866,12 @@ var ts; return token === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(206); + var node = createNode(208); parseExpected(96); parseExpected(17); node.expression = allowInAnd(parseExpression); parseExpected(18); - var caseBlock = createNode(220, scanner.getStartPos()); + var caseBlock = createNode(222, scanner.getStartPos()); parseExpected(15); caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); parseExpected(16); @@ -8628,14 +8879,14 @@ var ts; return finishNode(node); } function parseThrowStatement() { - var node = createNode(208); + var node = createNode(210); parseExpected(98); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(209); + var node = createNode(211); parseExpected(100); node.tryBlock = parseBlock(false); node.catchClause = token === 72 ? parseCatchClause() : undefined; @@ -8646,7 +8897,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(244); + var result = createNode(246); parseExpected(72); if (parseExpected(17)) { result.variableDeclaration = parseVariableDeclaration(); @@ -8656,7 +8907,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(210); + var node = createNode(212); parseExpected(76); parseSemicolon(); return finishNode(node); @@ -8665,13 +8916,13 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 69 && parseOptional(54)) { - var labeledStatement = createNode(207, fullStart); + var labeledStatement = createNode(209, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - var expressionStatement = createNode(195, fullStart); + var expressionStatement = createNode(197, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); @@ -8816,9 +9067,9 @@ var ts; case 86: return parseForOrForInOrForOfStatement(); case 75: - return parseBreakOrContinueStatement(202); + return parseBreakOrContinueStatement(204); case 70: - return parseBreakOrContinueStatement(203); + return parseBreakOrContinueStatement(205); case 94: return parseReturnStatement(); case 105: @@ -8888,7 +9139,7 @@ var ts; parseExportDeclaration(fullStart, decorators, modifiers); default: if (decorators || modifiers) { - var node = createMissingNode(231, true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(233, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; setModifiers(node, modifiers); @@ -8909,16 +9160,16 @@ var ts; } function parseArrayBindingElement() { if (token === 24) { - return createNode(187); + return createNode(189); } - var node = createNode(163); + var node = createNode(165); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(163); + var node = createNode(165); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== 54) { @@ -8933,14 +9184,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(161); + var node = createNode(163); parseExpected(15); node.elements = parseDelimitedList(9, parseObjectBindingElement); parseExpected(16); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(162); + var node = createNode(164); parseExpected(19); node.elements = parseDelimitedList(10, parseArrayBindingElement); parseExpected(20); @@ -8959,7 +9210,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(211); + var node = createNode(213); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -8968,7 +9219,7 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(212); + var node = createNode(214); switch (token) { case 102: break; @@ -8997,7 +9248,7 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 18; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(193, fullStart); + var node = createNode(195, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(false); @@ -9005,7 +9256,7 @@ var ts; return finishNode(node); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(213, fullStart); + var node = createNode(215, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(87); @@ -9091,7 +9342,7 @@ var ts; if (token === 55) { return true; } - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { idToken = token; if (isClassMemberModifier(idToken)) { return true; @@ -9134,7 +9385,7 @@ var ts; } if (!decorators) { decorators = []; - decorators.pos = scanner.getStartPos(); + decorators.pos = decoratorStart; } var decorator = createNode(139, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); @@ -9145,14 +9396,21 @@ var ts; } return decorators; } - function parseModifiers() { + function parseModifiers(permitInvalidConstAsModifier) { var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token; - if (!parseAnyContextualModifier()) { - break; + if (token === 74 && permitInvalidConstAsModifier) { + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } } if (!modifiers) { modifiers = []; @@ -9185,13 +9443,13 @@ var ts; } function parseClassElement() { if (token === 23) { - var result = createNode(191); + var result = createNode(193); nextToken(); return finishNode(result); } var fullStart = getNodePos(); var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var modifiers = parseModifiers(true); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; @@ -9210,16 +9468,16 @@ var ts; 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_7 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 186); + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 188); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 214); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 216); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); @@ -9252,12 +9510,9 @@ var ts; } return undefined; } - function parseHeritageClausesWorker() { - return parseList(20, parseHeritageClause); - } function parseHeritageClause() { if (token === 83 || token === 106) { - var node = createNode(243); + var node = createNode(245); node.token = token; nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); @@ -9266,7 +9521,7 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(188); + var node = createNode(190); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); @@ -9280,7 +9535,7 @@ var ts; return parseList(5, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(215, fullStart); + var node = createNode(217, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(107); @@ -9291,7 +9546,7 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(216, fullStart); + var node = createNode(218, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(132); @@ -9303,13 +9558,13 @@ var ts; return finishNode(node); } function parseEnumMember() { - var node = createNode(247, scanner.getStartPos()); + var node = createNode(249, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(217, fullStart); + var node = createNode(219, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(81); @@ -9324,7 +9579,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(219, scanner.getStartPos()); + var node = createNode(221, scanner.getStartPos()); if (parseExpected(15)) { node.statements = parseList(1, parseStatement); parseExpected(16); @@ -9335,7 +9590,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(218, fullStart); + var node = createNode(220, fullStart); var namespaceFlag = flags & 65536; node.decorators = decorators; setModifiers(node, modifiers); @@ -9347,7 +9602,7 @@ var ts; return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(218, fullStart); + var node = createNode(220, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parseLiteralNode(true); @@ -9377,11 +9632,6 @@ var ts; function nextTokenIsSlash() { return nextToken() === 39; } - function nextTokenIsCommaOrFromKeyword() { - nextToken(); - return token === 24 || - token === 133; - } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(89); var afterImportPos = scanner.getStartPos(); @@ -9389,7 +9639,7 @@ var ts; if (isIdentifier()) { identifier = parseIdentifier(); if (token !== 24 && token !== 133) { - var importEqualsDeclaration = createNode(221, fullStart); + var importEqualsDeclaration = createNode(223, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -9399,7 +9649,7 @@ var ts; return finishNode(importEqualsDeclaration); } } - var importDeclaration = createNode(222, fullStart); + var importDeclaration = createNode(224, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || @@ -9413,13 +9663,13 @@ var ts; return finishNode(importDeclaration); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(223, fullStart); + var importClause = createNode(225, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || parseOptional(24)) { - importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(225); + importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(227); } return finishNode(importClause); } @@ -9429,7 +9679,7 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(232); + var node = createNode(234); parseExpected(127); parseExpected(17); node.expression = parseModuleSpecifier(); @@ -9437,14 +9687,17 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - var result = parseExpression(); - if (result.kind === 9) { + if (token === 9) { + var result = parseLiteralNode(); internIdentifier(result.text); + return result; + } + else { + return parseExpression(); } - return result; } function parseNamespaceImport() { - var namespaceImport = createNode(224); + var namespaceImport = createNode(226); parseExpected(37); parseExpected(116); namespaceImport.name = parseIdentifier(); @@ -9452,14 +9705,14 @@ var ts; } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(21, kind === 225 ? parseImportSpecifier : parseExportSpecifier, 15, 16); + node.elements = parseBracketedList(21, kind === 227 ? parseImportSpecifier : parseExportSpecifier, 15, 16); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(230); + return parseImportOrExportSpecifier(232); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(226); + return parseImportOrExportSpecifier(228); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -9478,13 +9731,13 @@ var ts; else { node.name = identifierName; } - if (kind === 226 && checkIdentifierIsKeyword) { + if (kind === 228 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228, fullStart); + var node = createNode(230, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(37)) { @@ -9492,7 +9745,7 @@ var ts; node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(229); + node.exportClause = parseNamedImportsOrExports(231); if (token === 133 || (token === 9 && !scanner.hasPrecedingLineBreak())) { parseExpected(133); node.moduleSpecifier = parseModuleSpecifier(); @@ -9502,7 +9755,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(227, fullStart); + var node = createNode(229, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(56)) { @@ -9522,11 +9775,13 @@ var ts; var amdModuleName; while (true) { var kind = triviaScanner.scan(); - if (kind === 5 || kind === 4 || kind === 3) { - continue; - } if (kind !== 2) { - break; + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } } var range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; var comment = sourceText.substring(range.pos, range.end); @@ -9572,10 +9827,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return node.flags & 2 - || node.kind === 221 && node.moduleReference.kind === 232 - || node.kind === 222 - || node.kind === 227 - || node.kind === 228 + || node.kind === 223 && node.moduleReference.kind === 234 + || node.kind === 224 + || node.kind === 229 + || node.kind === 230 ? node : undefined; }); @@ -9610,7 +9865,7 @@ var ts; function parseJSDocTypeExpression(start, length) { scanner.setText(sourceText, start, length); token = nextToken(); - var result = createNode(249); + var result = createNode(251); parseExpected(15); result.type = parseJSDocTopLevelType(); parseExpected(16); @@ -9621,12 +9876,12 @@ var ts; function parseJSDocTopLevelType() { var type = parseJSDocType(); if (token === 47) { - var unionType = createNode(253, type.pos); + var unionType = createNode(255, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } if (token === 56) { - var optionalType = createNode(260, type.pos); + var optionalType = createNode(262, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -9637,20 +9892,20 @@ var ts; var type = parseBasicTypeExpression(); while (true) { if (token === 19) { - var arrayType = createNode(252, type.pos); + var arrayType = createNode(254, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20); type = finishNode(arrayType); } else if (token === 53) { - var nullableType = createNode(255, type.pos); + var nullableType = createNode(257, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } else if (token === 49) { - var nonNullableType = createNode(256, type.pos); + var nonNullableType = createNode(258, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -9694,27 +9949,27 @@ var ts; return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(264); + var result = createNode(266); nextToken(); parseExpected(54); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(263); + var result = createNode(265); nextToken(); parseExpected(54); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(262); + var result = createNode(264); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(261); + var result = createNode(263); nextToken(); parseExpected(17); result.parameters = parseDelimitedList(22, parseJSDocParameter); @@ -9731,14 +9986,8 @@ var ts; parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocOptionalType(type) { - var result = createNode(260, type.pos); - nextToken(); - result.type = type; - return finishNode(result); - } function parseJSDocTypeReference() { - var result = createNode(259); + var result = createNode(261); result.name = parseSimplePropertyName(); while (parseOptional(21)) { if (token === 25) { @@ -9773,7 +10022,7 @@ var ts; return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(257); + var result = createNode(259); nextToken(); result.members = parseDelimitedList(24, parseJSDocRecordMember); checkForTrailingComma(result.members); @@ -9781,7 +10030,7 @@ var ts; return finishNode(result); } function parseJSDocRecordMember() { - var result = createNode(258); + var result = createNode(260); result.name = parseSimplePropertyName(); if (token === 54) { nextToken(); @@ -9790,13 +10039,13 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(256); + var result = createNode(258); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(254); + var result = createNode(256); nextToken(); result.types = parseDelimitedList(25, parseJSDocType); checkForTrailingComma(result.types); @@ -9810,7 +10059,7 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(253); + var result = createNode(255); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); parseExpected(18); @@ -9828,7 +10077,7 @@ var ts; return types; } function parseJSDocAllType() { - var result = createNode(250); + var result = createNode(252); nextToken(); return finishNode(result); } @@ -9841,11 +10090,11 @@ var ts; token === 27 || token === 56 || token === 47) { - var result = createNode(251, pos); + var result = createNode(253, pos); return finishNode(result); } else { - var result = createNode(255, pos); + var result = createNode(257, pos); result.type = parseJSDocType(); return finishNode(result); } @@ -9916,7 +10165,7 @@ var ts; if (!tags) { return undefined; } - var result = createNode(265, start); + var result = createNode(267, start); result.tags = tags; return finishNode(result, end); } @@ -9953,7 +10202,7 @@ var ts; return undefined; } function handleUnknownTag(atToken, tagName) { - var result = createNode(266, atToken.pos); + var result = createNode(268, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result, pos); @@ -10004,7 +10253,7 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(267, atToken.pos); + var result = createNode(269, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; @@ -10014,27 +10263,27 @@ var ts; return finishNode(result, pos); } function handleReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 268; })) { + if (ts.forEach(tags, function (t) { return t.kind === 270; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(268, atToken.pos); + var result = createNode(270, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result, pos); } function handleTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 269; })) { + if (ts.forEach(tags, function (t) { return t.kind === 271; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(269, atToken.pos); + var result = createNode(271, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result, pos); } function handleTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 270; })) { + if (ts.forEach(tags, function (t) { return t.kind === 272; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } var typeParameters = []; @@ -10042,13 +10291,13 @@ var ts; while (true) { skipWhitespace(); var startPos = pos; - var name_9 = scanIdentifier(); - if (!name_9) { + var name_8 = scanIdentifier(); + if (!name_8) { parseErrorAtPosition(startPos, 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(137, name_9.pos); - typeParameter.name = name_9; + var typeParameter = createNode(137, name_8.pos); + typeParameter.name = name_8; finishNode(typeParameter, pos); typeParameters.push(typeParameter); skipWhitespace(); @@ -10058,7 +10307,7 @@ var ts; pos++; } typeParameters.end = pos; - var result = createNode(270, atToken.pos); + var result = createNode(272, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; @@ -10380,16 +10629,16 @@ var ts; : 4; } function getModuleInstanceState(node) { - if (node.kind === 215 || node.kind === 216) { + if (node.kind === 217 || node.kind === 218) { return 0; } else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 222 || node.kind === 221) && !(node.flags & 2)) { + else if ((node.kind === 224 || node.kind === 223) && !(node.flags & 2)) { return 0; } - else if (node.kind === 219) { + else if (node.kind === 221) { var state = 0; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -10405,7 +10654,7 @@ var ts; }); return state; } - else if (node.kind === 218) { + else if (node.kind === 220) { return getModuleInstanceState(node.body); } else { @@ -10448,6 +10697,8 @@ var ts; file.symbolCount = symbolCount; file.classifiableNames = classifiableNames; } + file = undefined; + options = undefined; parent = undefined; container = undefined; blockScopeContainer = undefined; @@ -10476,13 +10727,17 @@ var ts; if (symbolFlags & 6240 && !symbol.members) { symbol.members = {}; } - if (symbolFlags & 107455 && !symbol.valueDeclaration) { - symbol.valueDeclaration = node; + if (symbolFlags & 107455) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 220)) { + symbol.valueDeclaration = node; + } } } function getDeclarationName(node) { if (node.name) { - if (node.kind === 218 && node.name.kind === 9) { + if (node.kind === 220 && node.name.kind === 9) { return "\"" + node.name.text + "\""; } if (node.name.kind === 136) { @@ -10506,14 +10761,24 @@ var ts; return "__new"; case 149: return "__index"; - case 228: + case 230: return "__export"; - case 227: + case 229: return node.isExportEquals ? "export=" : "default"; - case 181: - return "export="; - case 213: - case 214: + case 183: + switch (ts.getSpecialPropertyAssignmentKind(node)) { + case 2: + return "export="; + case 1: + case 4: + return node.left.name.text; + case 3: + return node.left.expression.name.text; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 215: + case 216: return node.flags & 512 ? "default" : undefined; } } @@ -10561,7 +10826,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedNodeFlags(node) & 2; if (symbolFlags & 8388608) { - if (node.kind === 230 || (node.kind === 221 && hasExportModifier)) { + if (node.kind === 232 || (node.kind === 223 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -10608,10 +10873,10 @@ var ts; var kind = node.kind; var flags = node.flags; flags &= ~1572864; - if (kind === 215) { + if (kind === 217) { seenThisKeyword = false; } - var saveState = kind === 248 || kind === 219 || ts.isFunctionLikeKind(kind); + var saveState = kind === 250 || kind === 221 || ts.isFunctionLikeKind(kind); if (saveState) { savedReachabilityState = currentReachabilityState; savedLabelStack = labelStack; @@ -10629,7 +10894,7 @@ var ts; flags |= 1048576; } } - if (kind === 215) { + if (kind === 217) { flags = seenThisKeyword ? flags | 262144 : flags & ~262144; } node.flags = flags; @@ -10650,40 +10915,40 @@ var ts; return; } switch (node.kind) { - case 198: + case 200: bindWhileStatement(node); break; - case 197: + case 199: bindDoStatement(node); break; - case 199: + case 201: bindForStatement(node); break; - case 200: - case 201: + case 202: + case 203: bindForInOrForOfStatement(node); break; - case 196: + case 198: bindIfStatement(node); break; - case 204: - case 208: + case 206: + case 210: bindReturnOrThrow(node); break; - case 203: - case 202: + case 205: + case 204: bindBreakOrContinueStatement(node); break; - case 209: + case 211: bindTryStatement(node); break; - case 206: + case 208: bindSwitchStatement(node); break; - case 220: + case 222: bindCaseBlock(node); break; - case 207: + case 209: bindLabeledStatement(node); break; default: @@ -10745,14 +11010,14 @@ var ts; } function bindReturnOrThrow(n) { bind(n.expression); - if (n.kind === 204) { + if (n.kind === 206) { hasExplicitReturn = true; } currentReachabilityState = 4; } function bindBreakOrContinueStatement(n) { bind(n.label); - var isValidJump = jumpToLabel(n.label, n.kind === 203 ? currentReachabilityState : 4); + var isValidJump = jumpToLabel(n.label, n.kind === 205 ? currentReachabilityState : 4); if (isValidJump) { currentReachabilityState = 4; } @@ -10773,7 +11038,7 @@ var ts; var postSwitchLabel = pushImplicitLabel(); bind(n.expression); bind(n.caseBlock); - var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242; }); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 244; }); var postSwitchState = hasDefault && currentReachabilityState !== 2 ? 4 : preSwitchState; popImplicitLabel(postSwitchLabel, postSwitchState); } @@ -10798,37 +11063,37 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 186: - case 214: - case 215: + case 188: + case 216: case 217: + case 219: case 155: - case 165: + case 167: return 1; case 147: case 148: case 149: case 143: case 142: - case 213: + case 215: case 144: case 145: case 146: case 152: case 153: - case 173: - case 174: - case 218: - case 248: - case 216: - return 5; - case 244: - case 199: - case 200: - case 201: + case 175: + case 176: case 220: + case 250: + case 218: + return 5; + case 246: + case 201: + case 202: + case 203: + case 222: return 2; - case 192: + case 194: return ts.isFunctionLike(node.parent) ? 0 : 2; } return 0; @@ -10844,18 +11109,18 @@ var ts; } function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { switch (container.kind) { - case 218: + case 220: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 248: + case 250: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 186: - case 214: + case 188: + case 216: return declareClassMember(node, symbolFlags, symbolExcludes); - case 217: + case 219: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case 155: - case 165: - case 215: + case 167: + case 217: return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); case 152: case 153: @@ -10867,10 +11132,10 @@ var ts; case 144: case 145: case 146: - case 213: - case 173: - case 174: - case 216: + case 215: + case 175: + case 176: + case 218: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } @@ -10885,11 +11150,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 248 ? node : node.body; - if (body.kind === 248 || body.kind === 219) { + var body = node.kind === 250 ? node : node.body; + if (body.kind === 250 || body.kind === 221) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 228 || stat.kind === 227) { + if (stat.kind === 230 || stat.kind === 229) { return true; } } @@ -10948,7 +11213,7 @@ var ts; continue; } var identifier = prop.name; - var currentKind = prop.kind === 245 || prop.kind === 246 || prop.kind === 143 + var currentKind = prop.kind === 247 || prop.kind === 248 || prop.kind === 143 ? 1 : 2; var existingKind = seen[identifier.text]; @@ -10970,10 +11235,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 218: + case 220: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 248: + case 250: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -11095,17 +11360,17 @@ var ts; } function updateStrictMode(node) { switch (node.kind) { - case 248: - case 219: + case 250: + case 221: updateStrictModeStatementList(node.statements); return; - case 192: + case 194: if (ts.isFunctionLike(node.parent)) { updateStrictModeStatementList(node.statements); } return; - case 214: - case 186: + case 216: + case 188: inStrictMode = true; return; } @@ -11130,45 +11395,60 @@ var ts; switch (node.kind) { case 69: return checkStrictModeIdentifier(node); - case 181: + case 183: if (ts.isInJavaScriptFile(node)) { - if (ts.isExportsPropertyAssignment(node)) { - bindExportsPropertyAssignment(node); - } - else if (ts.isModuleExportsAssignment(node)) { - bindModuleExportsAssignment(node); + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1: + bindExportsPropertyAssignment(node); + break; + case 2: + bindModuleExportsAssignment(node); + break; + case 3: + bindPrototypePropertyAssignment(node); + break; + case 4: + bindThisPropertyAssignment(node); + break; + case 0: + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); } } return checkStrictModeBinaryExpression(node); - case 244: + case 246: return checkStrictModeCatchClause(node); - case 175: + case 177: return checkStrictModeDeleteExpression(node); case 8: return checkStrictModeNumericLiteral(node); - case 180: + case 182: return checkStrictModePostfixUnaryExpression(node); - case 179: + case 181: return checkStrictModePrefixUnaryExpression(node); - case 205: + case 207: return checkStrictModeWithStatement(node); - case 97: + case 161: seenThisKeyword = true; return; + case 150: + return checkTypePredicate(node); case 137: return declareSymbolAndAddToSymbolTable(node, 262144, 530912); case 138: return bindParameter(node); - case 211: - case 163: + case 213: + case 165: return bindVariableDeclarationOrBindingElement(node); case 141: case 140: return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455); - case 245: - case 246: - return bindPropertyOrMethodOrAccessor(node, 4, 107455); case 247: + case 248: + return bindPropertyOrMethodOrAccessor(node, 4, 107455); + case 249: return bindPropertyOrMethodOrAccessor(node, 8, 107455); case 147: case 148: @@ -11177,7 +11457,7 @@ var ts; case 143: case 142: return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263); - case 213: + case 215: checkStrictModeFunctionName(node); return declareSymbolAndAddToSymbolTable(node, 16, 106927); case 144: @@ -11191,44 +11471,54 @@ var ts; return bindFunctionOrConstructorType(node); case 155: return bindAnonymousDeclaration(node, 2048, "__type"); - case 165: + case 167: return bindObjectLiteralExpression(node); - case 173: - case 174: + case 175: + case 176: checkStrictModeFunctionName(node); var bindingName = node.name ? node.name.text : "__function"; return bindAnonymousDeclaration(node, 16, bindingName); - case 168: + case 170: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; - case 186: - case 214: - return bindClassLikeDeclaration(node); - case 215: - return bindBlockScopedDeclaration(node, 64, 792960); + case 188: case 216: - return bindBlockScopedDeclaration(node, 524288, 793056); + return bindClassLikeDeclaration(node); case 217: - return bindEnumDeclaration(node); + return bindBlockScopedDeclaration(node, 64, 792960); case 218: + return bindBlockScopedDeclaration(node, 524288, 793056); + case 219: + return bindEnumDeclaration(node); + case 220: return bindModuleDeclaration(node); - case 221: - case 224: - case 226: - case 230: - return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); case 223: - return bindImportClause(node); + case 226: case 228: + case 232: + return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + case 225: + return bindImportClause(node); + case 230: return bindExportDeclaration(node); - case 227: + case 229: return bindExportAssignment(node); - case 248: + case 250: return bindSourceFileIfExternalModule(); } } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 69) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 161) { + seenThisKeyword = true; + } + bind(type); + } function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (ts.isExternalModule(file)) { @@ -11239,7 +11529,7 @@ var ts; bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { - var boundExpression = node.kind === 227 ? node.expression : node.right; + var boundExpression = node.kind === 229 ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } @@ -11277,13 +11567,30 @@ var ts; setCommonJsModuleIndicator(node); bindExportAssignment(node); } + function bindThisPropertyAssignment(node) { + if (container.kind === 175 || container.kind === 215) { + container.symbol.members = container.symbol.members || {}; + declareSymbol(container.symbol.members, container.symbol, node, 4, 107455); + } + } + function bindPrototypePropertyAssignment(node) { + var classId = node.left.expression.expression; + var funcSymbol = container.locals[classId.text]; + if (!funcSymbol || !(funcSymbol.flags & 16)) { + return; + } + if (!funcSymbol.members) { + funcSymbol.members = {}; + } + declareSymbol(funcSymbol.members, funcSymbol, node.left, 4, 107455); + } function bindCallExpression(node) { if (!file.commonJsModuleIndicator && ts.isRequireCall(node)) { setCommonJsModuleIndicator(node); } } function bindClassLikeDeclaration(node) { - if (node.kind === 214) { + if (node.kind === 216) { bindBlockScopedDeclaration(node, 32, 899519); } else { @@ -11335,9 +11642,7 @@ var ts; else { declareSymbolAndAddToSymbolTable(node, 1, 107455); } - if (node.flags & 56 && - node.parent.kind === 144 && - ts.isClassLike(node.parent.parent)) { + if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); } @@ -11402,15 +11707,15 @@ var ts; function checkUnreachable(node) { switch (currentReachabilityState) { case 4: - var reportError = (ts.isStatement(node) && node.kind !== 194) || - node.kind === 214 || - (node.kind === 218 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 217 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + var reportError = (ts.isStatement(node) && node.kind !== 196) || + node.kind === 216 || + (node.kind === 220 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 219 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentReachabilityState = 8; var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && - (node.kind !== 193 || + (node.kind !== 195 || ts.getCombinedNodeFlags(node.declarationList) & 24576 || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -11444,15 +11749,18 @@ var ts; var nextNodeId = 1; var nextMergeId = 1; function getNodeId(node) { - if (!node.id) - node.id = nextNodeId++; + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } return node.id; } ts.getNodeId = getNodeId; ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { - symbol.id = nextSymbolId++; + symbol.id = nextSymbolId; + nextSymbolId++; } return symbol.id; } @@ -11469,8 +11777,10 @@ var ts; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0; var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 ? 5 : 0; + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === 4; var emitResolver = createResolver(); var undefinedSymbol = createSymbol(4 | 67108864, "undefined"); + undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 | 67108864, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -11482,6 +11792,7 @@ var ts; getDiagnostics: getDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, getTypeOfSymbolAtLocation: getNarrowedTypeOfSymbol, + getSymbolsOfParameterPropertyDeclaration: getSymbolsOfParameterPropertyDeclaration, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: getPropertyOfType, @@ -11498,7 +11809,7 @@ var ts; symbolToString: symbolToString, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: getApparentTypeOfContextualType, + getContextualType: getContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: getResolvedSignature, getConstantValue: getConstantValue, @@ -11523,15 +11834,15 @@ var ts; var undefinedType = createIntrinsicType(32 | 2097152, "undefined"); var nullType = createIntrinsicType(64 | 2097152, "null"); var unknownType = createIntrinsicType(1, "unknown"); - var circularType = createIntrinsicType(1, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyUnionType = emptyObjectType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); anyFunctionType.flags |= 8388608; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); var globals = {}; var globalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; @@ -11544,8 +11855,6 @@ var ts; var globalRegExpType; var globalTemplateStringsArrayType; var globalESSymbolType; - var jsxElementType; - var jsxIntrinsicElementsType; var globalIterableType; var globalIteratorType; var globalIterableIteratorType; @@ -11562,6 +11871,7 @@ var ts; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; var jsxElementClassType; + var deferredNodes; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; @@ -11596,19 +11906,31 @@ var ts; "symbol": { type: esSymbolType, flags: 16777216 + }, + "undefined": { + type: undefinedType, + flags: 2097152 } }; + var jsxElementType; + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", ElementClass: "ElementClass", ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - Element: "Element" + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" }; var subtypeRelation = {}; var assignableRelation = {}; var identityRelation = {}; var _displayBuilder; + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -11662,8 +11984,10 @@ var ts; return result; } function recordMergedSymbol(target, source) { - if (!source.mergeId) - source.mergeId = nextMergeId++; + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { @@ -11687,8 +12011,11 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (!target.valueDeclaration && source.valueDeclaration) + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 220 && source.valueDeclaration.kind !== 220))) { target.valueDeclaration = source.valueDeclaration; + } ts.forEach(source.declarations, function (node) { target.declarations.push(node); }); @@ -11740,6 +12067,21 @@ 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]; + } + } + } + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } function getSymbolLinks(symbol) { if (symbol.flags & 67108864) return symbol; @@ -11751,10 +12093,16 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function getSourceFile(node) { - return ts.getAncestor(node, 248); + return ts.getAncestor(node, 250); } function isGlobalSourceFile(node) { - return node.kind === 248 && !ts.isExternalOrCommonJsModule(node); + return node.kind === 250 && !ts.isExternalOrCommonJsModule(node); + } + function isPrimitiveApparentType(type) { + return type === globalStringType || + type === globalNumberType || + type === globalBooleanType || + type === globalESSymbolType; } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -11771,6 +12119,16 @@ var ts; } } } + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructoDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructoDeclaration.locals, parameterName, 107455); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); @@ -11782,18 +12140,18 @@ var ts; return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { - return declaration.kind !== 211 || + return declaration.kind !== 213 || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } return isUsedInFunctionOrNonStaticProperty(declaration, usage); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); - if (declaration.parent.parent.kind === 193 || - declaration.parent.parent.kind === 199) { + if (declaration.parent.parent.kind === 195 || + declaration.parent.parent.kind === 201) { return isSameScopeDescendentOf(usage, declaration, container); } - else if (declaration.parent.parent.kind === 201 || - declaration.parent.parent.kind === 200) { + else if (declaration.parent.parent.kind === 203 || + declaration.parent.parent.kind === 202) { var expression = declaration.parent.parent.expression; return isSameScopeDescendentOf(usage, expression, container); } @@ -11829,23 +12187,38 @@ var ts; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { - if (!(meaning & 793056) || - !(result.flags & (793056 & ~262144)) || - !ts.isFunctionLike(location) || - lastLocation === location.body) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + if (meaning & result.flags & 793056) { + useResult = result.flags & 262144 + ? lastLocation === location.type || + lastLocation.kind === 138 || + lastLocation.kind === 137 + : false; + } + if (meaning & 107455 && result.flags & 1) { + useResult = + lastLocation.kind === 138 || + (lastLocation === location.type && + result.valueDeclaration.kind === 138); + } + } + if (useResult) { break loop; } - result = undefined; + else { + result = undefined; + } } } switch (location.kind) { - case 248: + case 250: if (!ts.isExternalOrCommonJsModule(location)) break; - case 218: + case 220: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 248 || - (location.kind === 218 && location.name.kind === 9)) { + if (location.kind === 250 || + (location.kind === 220 && location.name.kind === 9)) { if (result = moduleExports["default"]) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { @@ -11855,7 +12228,7 @@ var ts; } if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 && - ts.getDeclarationOfKind(moduleExports[name], 230)) { + ts.getDeclarationOfKind(moduleExports[name], 232)) { break; } } @@ -11863,7 +12236,7 @@ var ts; break loop; } break; - case 217: + case 219: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } @@ -11879,9 +12252,9 @@ var ts; } } break; - case 214: - case 186: - case 215: + case 216: + case 188: + case 217: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { if (lastLocation && lastLocation.flags & 64) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); @@ -11889,7 +12262,7 @@ var ts; } break loop; } - if (location.kind === 186 && meaning & 32) { + if (location.kind === 188 && meaning & 32) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -11899,7 +12272,7 @@ var ts; break; case 136: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 215) { + if (ts.isClassLike(grandparent) || grandparent.kind === 217) { if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; @@ -11911,14 +12284,14 @@ var ts; case 144: case 145: case 146: - case 213: - case 174: + case 215: + case 176: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 173: + case 175: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -11971,7 +12344,7 @@ var ts; ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 211), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 213), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -11988,10 +12361,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 221) { + if (node.kind === 223) { return node; } - while (node && node.kind !== 222) { + while (node && node.kind !== 224) { node = node.parent; } return node; @@ -12001,7 +12374,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 232) { + if (node.moduleReference.kind === 234) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -12010,9 +12383,12 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); - if (!exportDefaultSymbol) { + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveSymbol(moduleSymbol.exports["export="]) || resolveSymbol(moduleSymbol); + } return exportDefaultSymbol; } } @@ -12020,14 +12396,6 @@ var ts; var moduleSpecifier = node.parent.parent.moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } - function getMemberOfModuleVariable(moduleSymbol, name) { - if (moduleSymbol.flags & 3) { - var typeAnnotation = moduleSymbol.valueDeclaration.type; - if (typeAnnotation) { - return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); - } - } - } function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { if (valueSymbol.flags & (793056 | 1536)) { return valueSymbol; @@ -12063,15 +12431,15 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_10 = specifier.propertyName || specifier.name; - if (name_10.text) { - var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); - var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_10.text); + var name_9 = specifier.propertyName || specifier.name; + if (name_9.text) { + var symbolFromModule = getExportOfModule(targetSymbol, name_9.text); + var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_9.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_10, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_10)); + error(name_9, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_9)); } return symbol; } @@ -12090,17 +12458,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 221: - return getTargetOfImportEqualsDeclaration(node); case 223: + return getTargetOfImportEqualsDeclaration(node); + case 225: return getTargetOfImportClause(node); - case 224: - return getTargetOfNamespaceImport(node); case 226: + return getTargetOfNamespaceImport(node); + case 228: return getTargetOfImportSpecifier(node); - case 230: + case 232: return getTargetOfExportSpecifier(node); - case 227: + case 229: return getTargetOfExportAssignment(node); } } @@ -12142,10 +12510,10 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 227) { + if (node.kind === 229) { checkExpressionCached(node.expression); } - else if (node.kind === 230) { + else if (node.kind === 232) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -12155,7 +12523,7 @@ var ts; } function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 221); + importDeclaration = ts.getAncestor(entityName, 223); ts.Debug.assert(importDeclaration !== undefined); } if (entityName.kind === 69 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { @@ -12165,7 +12533,7 @@ var ts; return resolveEntityName(entityName, 1536); } else { - ts.Debug.assert(entityName.parent.kind === 221); + ts.Debug.assert(entityName.parent.kind === 223); return resolveEntityName(entityName, 107455 | 793056 | 1536); } } @@ -12184,7 +12552,7 @@ var ts; return undefined; } } - else if (name.kind === 135 || name.kind === 166) { + else if (name.kind === 135 || name.kind === 168) { var left = name.kind === 135 ? name.left : name.expression; var right = name.kind === 135 ? name.right : name.name; var namespace = resolveEntityName(left, 1536, ignoreErrors); @@ -12210,14 +12578,10 @@ var ts; return; } var moduleReferenceLiteral = moduleReferenceExpression; - var searchPath = ts.getDirectoryPath(getSourceFile(location).fileName); var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); if (moduleName === undefined) { return; } - if (moduleName.indexOf("!") >= 0) { - moduleName = moduleName.substr(0, moduleName.indexOf("!")); - } var isRelative = ts.isExternalModuleNameRelative(moduleName); if (!isRelative) { var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); @@ -12260,35 +12624,58 @@ var ts; var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } - function extendExportSymbols(target, source) { + function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; + if (lookupTable && exportNode) { + lookupTable[id] = { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }; + } + } + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + if (!lookupTable[id].exportsWithDuplicate) { + lookupTable[id].exportsWithDuplicate = [exportNode]; + } + else { + lookupTable[id].exportsWithDuplicate.push(exportNode); + } } } } function getExportsForModule(moduleSymbol) { - var result; var visitedSymbols = []; - visit(moduleSymbol); - return result || moduleSymbol.exports; + return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { - if (symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol)) { - visitedSymbols.push(symbol); - if (symbol !== moduleSymbol) { - if (!result) { - result = cloneSymbolTable(moduleSymbol.exports); - } - extendExportSymbols(result, symbol.exports); - } - var exportStars = symbol.exports["__export"]; - if (exportStars) { - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - visit(resolveExternalModuleName(node, node.moduleSpecifier)); - } - } + if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { + return; } + visitedSymbols.push(symbol); + var symbols = cloneSymbolTable(symbol.exports); + var exportStars = symbol.exports["__export"]; + if (exportStars) { + var nestedSymbols = {}; + var lookupTable = {}; + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node); + } + for (var id in lookupTable) { + var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + continue; + } + for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { + var node = exportsWithDuplicate_1[_b]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable[id].specifierText, id)); + } + } + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; } } function getMergedSymbol(symbol) { @@ -12329,7 +12716,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount++; + result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -12387,17 +12775,17 @@ var ts; } } switch (location_1.kind) { - case 248: + case 250: if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 218: + case 220: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 214: - case 215: + case 216: + case 217: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -12430,7 +12818,7 @@ var ts; return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230)) { + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 232)) { if (!useOnlyExternalAliasing || ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); @@ -12459,7 +12847,7 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 232)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -12514,8 +12902,8 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 218 && declaration.name.kind === 9) || - (declaration.kind === 248 && ts.isExternalOrCommonJsModule(declaration)); + return (declaration.kind === 220 && declaration.name.kind === 9) || + (declaration.kind === 250 && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -12550,8 +12938,8 @@ var ts; if (entityName.parent.kind === 154) { meaning = 107455 | 1048576; } - else if (entityName.kind === 135 || entityName.kind === 166 || - entityName.parent.kind === 221) { + else if (entityName.kind === 135 || entityName.kind === 168 || + entityName.parent.kind === 223) { meaning = 1536; } else { @@ -12581,9 +12969,9 @@ var ts; ts.releaseStringWriter(writer); return result; } - function signatureToString(signature, enclosingDeclaration, flags) { + function signatureToString(signature, enclosingDeclaration, flags, kind) { var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); var result = writer.string(); ts.releaseStringWriter(writer); return result; @@ -12605,7 +12993,7 @@ var ts; while (node.kind === 160) { node = node.parent; } - if (node.kind === 216) { + if (node.kind === 218) { return getSymbolOfNode(node); } } @@ -12619,10 +13007,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 186: + case 188: return "(Anonymous class)"; - case 173: - case 174: + case 175: + case 176: return "(Anonymous function)"; } } @@ -12687,9 +13075,15 @@ var ts; return writeType(type, globalFlags); function writeType(type, flags) { if (type.flags & 16777343) { - writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) - ? "any" - : type.intrinsicName); + if (type.flags & 134217728) { + buildTypePredicateDisplay(writer, type.predicate); + buildTypeDisplay(type.predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } + else { + writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) + ? "any" + : type.intrinsicName); + } } else if (type.flags & 33554432) { if (inObjectTypeLiteral) { @@ -12741,11 +13135,13 @@ var ts; } if (pos < end) { writePunctuation(writer, 25); - writeType(typeArguments[pos++], 0); + writeType(typeArguments[pos], 0); + pos++; while (pos < end) { writePunctuation(writer, 24); writeSpace(writer); - writeType(typeArguments[pos++], 0); + writeType(typeArguments[pos], 0); + pos++; } writePunctuation(writer, 27); } @@ -12828,7 +13224,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 248 || declaration.parent.kind === 219; + return declaration.parent.kind === 250 || declaration.parent.kind === 221; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 2) || @@ -12861,7 +13257,7 @@ var ts; if (flags & 64) { writePunctuation(writer, 17); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (flags & 64) { writePunctuation(writer, 18); } @@ -12873,7 +13269,7 @@ var ts; } writeKeyword(writer, 92); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (flags & 64) { writePunctuation(writer, 18); } @@ -12887,15 +13283,13 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - writeKeyword(writer, 92); - writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } @@ -12936,7 +13330,7 @@ var ts; if (p.flags & 536870912) { writePunctuation(writer, 53); } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } @@ -13024,6 +13418,17 @@ var ts; } writePunctuation(writer, 18); } + function buildTypePredicateDisplay(writer, predicate) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 97); + } + writeSpace(writer); + writeKeyword(writer, 124); + writeSpace(writer); + } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8) { writeSpace(writer); @@ -13033,20 +13438,14 @@ var ts; writePunctuation(writer, 54); } writeSpace(writer); - var returnType; - if (signature.typePredicate) { - writer.writeParameter(signature.typePredicate.parameterName); - writeSpace(writer); - writeKeyword(writer, 124); - writeSpace(writer); - returnType = signature.typePredicate.type; - } - else { - returnType = getReturnTypeOfSignature(signature); - } + var returnType = getReturnTypeOfSignature(signature); buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1) { + writeKeyword(writer, 92); + writeSpace(writer); + } if (signature.target && (flags & 32)) { buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); } @@ -13069,73 +13468,33 @@ var ts; }); } function isDeclarationVisible(node) { - function getContainingExternalModule(node) { - for (; node; node = node.parent) { - if (node.kind === 218) { - if (node.name.kind === 9) { - return node; - } - } - else if (node.kind === 248) { - return ts.isExternalOrCommonJsModule(node) ? node : undefined; - } - } - ts.Debug.fail("getContainingModule cant reach here"); - } - function isUsedInExportAssignment(node) { - var externalModule = getContainingExternalModule(node); - var exportAssignmentSymbol; - var resolvedExportSymbol; - if (externalModule) { - var externalModuleSymbol = getSymbolOfNode(externalModule); - exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); - var symbolOfNode = getSymbolOfNode(node); - if (isSymbolUsedInExportAssignment(symbolOfNode)) { - return true; - } - if (symbolOfNode.flags & 8388608) { - return isSymbolUsedInExportAssignment(resolveAlias(symbolOfNode)); - } - } - function isSymbolUsedInExportAssignment(symbol) { - if (exportAssignmentSymbol === symbol) { - return true; - } - if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 8388608)) { - resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol); - if (resolvedExportSymbol === symbol) { - return true; - } - return ts.forEach(resolvedExportSymbol.declarations, function (current) { - while (current) { - if (current === node) { - return true; - } - current = current.parent; - } - }); - } + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); } + return links.isVisible; } + return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 163: + case 165: return isDeclarationVisible(node.parent.parent); - case 211: + case 213: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { return false; } - case 218: - case 214: - case 215: + case 220: case 216: - case 213: case 217: - case 221: + case 218: + case 215: + case 219: + case 223: var parent_4 = getDeclarationContainer(node); if (!(ts.getCombinedNodeFlags(node) & 2) && - !(node.kind !== 221 && parent_4.kind !== 248 && ts.isInAmbientContext(parent_4))) { + !(node.kind !== 223 && parent_4.kind !== 250 && ts.isInAmbientContext(parent_4))) { return isGlobalSourceFile(parent_4); } return isDeclarationVisible(parent_4); @@ -13153,7 +13512,7 @@ var ts; case 147: case 149: case 138: - case 219: + case 221: case 152: case 153: case 155: @@ -13164,33 +13523,26 @@ var ts; case 159: case 160: return isDeclarationVisible(node.parent); - case 223: - case 224: + case 225: case 226: + case 228: return false; case 137: - case 248: + case 250: return true; - case 227: + case 229: return false; default: ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); } } - if (node) { - var links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 227) { + if (node.parent && node.parent.kind === 229) { exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 230) { + else if (node.parent.kind === 232) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -13265,7 +13617,7 @@ var ts; } function getDeclarationContainer(node) { node = ts.getRootDeclaration(node); - return node.kind === 211 ? node.parent.parent.parent : node.parent; + return node.kind === 213 ? node.parent.parent.parent : node.parent; } function getTypeOfPrototypeProperty(prototype) { var classType = getDeclaredTypeOfSymbol(prototype.parent); @@ -13312,17 +13664,17 @@ var ts; return parentType; } var type; - if (pattern.kind === 161) { - var name_11 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_11)) { + if (pattern.kind === 163) { + var name_10 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_10)) { return anyType; } - var text = getTextOfPropertyName(name_11); + var text = getTextOfPropertyName(name_10); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_11, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_11)); + error(name_10, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_10)); return unknownType; } } @@ -13350,10 +13702,10 @@ var ts; return type; } function getTypeForVariableLikeDeclaration(declaration) { - if (declaration.parent.parent.kind === 200) { + if (declaration.parent.parent.kind === 202) { return anyType; } - if (declaration.parent.parent.kind === 201) { + if (declaration.parent.parent.kind === 203) { return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -13378,7 +13730,7 @@ var ts; if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } - if (declaration.kind === 246) { + if (declaration.kind === 248) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { @@ -13425,7 +13777,7 @@ var ts; 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 === 187 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return e.kind === 189 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { var result = createNewTupleType(elementTypes); result.pattern = pattern; @@ -13434,7 +13786,7 @@ var ts; return createTupleType(elementTypes); } function getTypeFromBindingPattern(pattern, includePatternInType) { - return pattern.kind === 161 + return pattern.kind === 163 ? getTypeFromObjectBindingPattern(pattern, includePatternInType) : getTypeFromArrayBindingPattern(pattern, includePatternInType); } @@ -13444,7 +13796,13 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - return declaration.kind !== 245 ? getWidenedType(type) : type; + if (declaration.kind === 247) { + return type; + } + if (type.flags & 134217728 && (declaration.kind === 141 || declaration.kind === 140)) { + return type; + } + return getWidenedType(type); } type = declaration.dotDotDotToken ? anyArrayType : anyType; if (reportErrors && compilerOptions.noImplicitAny) { @@ -13462,17 +13820,19 @@ var ts; return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 244) { + if (declaration.parent.kind === 246) { return links.type = anyType; } - if (declaration.kind === 227) { + if (declaration.kind === 229) { return links.type = checkExpression(declaration.expression); } - if (declaration.kind === 181) { + if (declaration.kind === 183) { return links.type = checkExpression(declaration.right); } - if (declaration.kind === 166) { - return checkExpressionCached(declaration.parent.right); + if (declaration.kind === 168) { + if (declaration.parent.kind === 183) { + return links.type = checkExpressionCached(declaration.parent.right); + } } if (!pushTypeResolution(symbol, 0)) { return unknownType; @@ -13628,9 +13988,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 214 || node.kind === 186 || - node.kind === 213 || node.kind === 173 || - node.kind === 143 || node.kind === 174) { + if (node.kind === 216 || node.kind === 188 || + node.kind === 215 || node.kind === 175 || + node.kind === 143 || node.kind === 176) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -13639,15 +13999,15 @@ var ts; } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 215); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 217); return appendOuterTypeParameters(undefined, declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 215 || node.kind === 214 || - node.kind === 186 || node.kind === 216) { + if (node.kind === 217 || node.kind === 216 || + node.kind === 188 || node.kind === 218) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -13702,9 +14062,6 @@ var ts; } return type.resolvedBaseConstructorType; } - function hasClassBaseType(type) { - return !!ts.forEach(getBaseTypes(type), function (t) { return !!(t.symbol.flags & 32); }); - } function getBaseTypes(type) { var isClass = type.symbol.flags & 32; var isInterface = type.symbol.flags & 64; @@ -13773,7 +14130,7 @@ var ts; type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 217 && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -13802,7 +14159,7 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215) { + if (declaration.kind === 217) { if (declaration.flags & 262144) { return false; } @@ -13851,7 +14208,7 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 216); + var declaration = ts.getDeclarationOfKind(symbol, 218); var type = getTypeFromTypeNode(declaration.type); if (popTypeResolution()) { links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -13934,7 +14291,7 @@ var ts; case 120: case 131: case 103: - case 9: + case 162: return true; case 156: return isIndependentType(node.elementType); @@ -13999,14 +14356,6 @@ var ts; } } } - function addInheritedSignatures(signatures, baseSignatures) { - if (baseSignatures) { - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var signature = baseSignatures_1[_i]; - signatures.push(signature); - } - } - } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; @@ -14067,33 +14416,32 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, parameters, resolvedReturnType, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - if (!hasClassBaseType(classType)) { - return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, 0, false, false)]; + } var baseTypeNode = getBaseTypeNodeOfClass(classType); var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { - var baseSig = baseSignatures_2[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -14123,7 +14471,7 @@ var ts; function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreReturnTypes, compareTypesIdentical)) { return s; } } @@ -14212,35 +14560,28 @@ var ts; } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; - var members; - var callSignatures; - var constructSignatures; - var stringIndexType; - var numberIndexType; if (type.target) { - members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); - callSignatures = instantiateList(getSignaturesOfType(type.target, 0), type.mapper, instantiateSignature); - constructSignatures = instantiateList(getSignaturesOfType(type.target, 1), type.mapper, instantiateSignature); - stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0), type.mapper); - numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1), type.mapper); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); + var callSignatures = instantiateList(getSignaturesOfType(type.target, 0), type.mapper, instantiateSignature); + var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1), type.mapper, instantiateSignature); + var stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0), type.mapper); + var numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1), type.mapper); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } else if (symbol.flags & 2048) { - members = symbol.members; - callSignatures = getSignaturesOfSymbol(members["__call"]); - constructSignatures = getSignaturesOfSymbol(members["__new"]); - stringIndexType = getIndexTypeOfSymbol(symbol, 0); - numberIndexType = getIndexTypeOfSymbol(symbol, 1); + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members["__call"]); + var constructSignatures = getSignaturesOfSymbol(members["__new"]); + var stringIndexType = getIndexTypeOfSymbol(symbol, 0); + var numberIndexType = getIndexTypeOfSymbol(symbol, 1); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } else { - members = emptySymbols; - callSignatures = emptyArray; - constructSignatures = emptyArray; + var members = emptySymbols; + var constructSignatures = emptyArray; if (symbol.flags & 1952) { members = getExportsOfSymbol(symbol); } - if (symbol.flags & (16 | 8192)) { - callSignatures = getSignaturesOfSymbol(symbol); - } if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); @@ -14253,10 +14594,12 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } - stringIndexType = undefined; - numberIndexType = (symbol.flags & 384) ? stringType : undefined; + var numberIndexType = (symbol.flags & 384) ? stringType : undefined; + setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexType); + if (symbol.flags & (16 | 8192)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -14346,12 +14689,14 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; + var commonFlags = (containingType.flags & 32768) ? 536870912 : 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 | 32))) { + commonFlags &= prop.flags; if (!props) { props = [prop]; } @@ -14379,7 +14724,10 @@ var ts; } propTypes.push(getTypeOfSymbol(prop)); } - var result = createSymbol(4 | 67108864 | 268435456, name); + var result = createSymbol(4 | + 67108864 | + 268435456 | + commonFlags, name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & 16384 ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -14429,22 +14777,6 @@ var ts; function getSignaturesOfType(type, kind) { return getSignaturesOfStructuredType(getApparentType(type), kind); } - function typeHasConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & (80896 | 16384)) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.constructSignatures.length > 0; - } - return false; - } - function typeHasCallOrConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & 130048) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; - } - return false; - } function getIndexTypeOfStructuredType(type, kind) { if (type.flags & 130048) { var resolved = resolveStructuredTypeMembers(type); @@ -14486,6 +14818,23 @@ var ts; } return false; } + function createTypePredicateFromTypePredicateNode(node) { + if (node.parameterName.kind === 69) { + var parameterName = node.parameterName; + return { + kind: 1, + parameterName: parameterName ? parameterName.text : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0, + type: getTypeFromTypeNode(node.type) + }; + } + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { @@ -14499,8 +14848,13 @@ var ts; var minArgumentCount = -1; for (var i = 0, n = declaration.parameters.length; i < n; i++) { var param = declaration.parameters[i]; - parameters.push(param.symbol); - if (param.type && param.type.kind === 9) { + var paramSymbol = param.symbol; + if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.name, 107455, undefined, undefined); + paramSymbol = resolvedSymbol; + } + parameters.push(paramSymbol); + if (param.type && param.type.kind === 162) { hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken) { @@ -14516,20 +14870,11 @@ var ts; minArgumentCount = declaration.parameters.length; } var returnType; - var typePredicate; if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); - if (declaration.type.kind === 150) { - var typePredicateNode = declaration.type; - typePredicate = { - parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, - parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, - type: getTypeFromTypeNode(typePredicateNode.type) - }; - } } else { if (declaration.kind === 145 && !ts.hasDynamicName(declaration)) { @@ -14540,7 +14885,7 @@ var ts; returnType = anyType; } } - links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -14553,7 +14898,7 @@ var ts; switch (node.kind) { case 152: case 153: - case 213: + case 215: case 143: case 142: case 144: @@ -14562,8 +14907,8 @@ var ts; case 149: case 145: case 146: - case 173: - case 174: + case 175: + case 176: if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -14679,17 +15024,38 @@ var ts; ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType : undefined; } - function getConstraintOfTypeParameter(type) { - if (!type.constraint) { - if (type.target) { - var targetConstraint = getConstraintOfTypeParameter(type.target); - type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 137).constraint; + } + function hasConstraintReferenceTo(type, target) { + var checked; + while (type && type.flags & 512 && !ts.contains(checked, type)) { + if (type === target) { + return true; + } + (checked || (checked = [])).push(type); + var constraintDeclaration = getConstraintDeclaration(type); + type = constraintDeclaration && getTypeFromTypeNode(constraintDeclaration); + } + return false; + } + function getConstraintOfTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 137).constraint); + var constraintDeclaration = getConstraintDeclaration(typeParameter); + var constraint = getTypeFromTypeNode(constraintDeclaration); + if (hasConstraintReferenceTo(constraint, typeParameter)) { + error(constraintDeclaration, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + constraint = unknownType; + } + typeParameter.constraint = constraint; } } - return type.constraint === noConstraintType ? undefined : type.constraint; + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 137).parent); @@ -14733,40 +15099,6 @@ var ts; } return type; } - function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode, typeParameterSymbol) { - var links = getNodeLinks(typeReferenceNode); - if (links.isIllegalTypeReferenceInConstraint !== undefined) { - return links.isIllegalTypeReferenceInConstraint; - } - var currentNode = typeReferenceNode; - while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { - currentNode = currentNode.parent; - } - links.isIllegalTypeReferenceInConstraint = currentNode.kind === 137; - return links.isIllegalTypeReferenceInConstraint; - } - function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { - var typeParameterSymbol; - function check(n) { - if (n.kind === 151 && n.typeName.kind === 69) { - var links = getNodeLinks(n); - if (links.isIllegalTypeReferenceInConstraint === undefined) { - var symbol = resolveName(typeParameter, n.typeName.text, 793056, undefined, undefined); - if (symbol && (symbol.flags & 262144)) { - links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent === typeParameter.parent; }); - } - } - if (links.isIllegalTypeReferenceInConstraint) { - error(typeParameter, ts.Diagnostics.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); - } - } - ts.forEachChild(n, check); - } - if (typeParameter.constraint) { - typeParameterSymbol = getSymbolOfNode(typeParameter); - check(typeParameter.constraint); - } - } function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = type.localTypeParameters; @@ -14803,9 +15135,6 @@ var ts; return type; } function getTypeFromNonGenericTypeReference(node, symbol) { - if (symbol.flags & 262144 && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { - return unknownType; - } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); return unknownType; @@ -14841,9 +15170,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 214: - case 215: + case 216: case 217: + case 219: return declaration; } } @@ -14875,10 +15204,6 @@ var ts; if (arity === void 0) { arity = 0; } return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } - function tryGetGlobalType(name, arity) { - if (arity === void 0) { arity = 0; } - return getTypeOfGlobalSymbol(getGlobalSymbol(name, 793056, undefined), arity); - } function getExportedTypeFromNamespace(namespace, name) { var namespaceSymbol = getGlobalSymbol(namespace, 1536, undefined); var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056); @@ -14979,7 +15304,7 @@ var ts; } function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { - return emptyObjectType; + return emptyUnionType; } var typeSet = []; addTypesToSet(typeSet, types, 16384); @@ -15045,8 +15370,7 @@ var ts; } return links.resolvedType; } - function getStringLiteralType(node) { - var text = node.text; + function getStringLiteralTypeForText(text) { if (ts.hasProperty(stringLiteralTypes, text)) { return stringLiteralTypes[text]; } @@ -15054,17 +15378,17 @@ var ts; type.text = text; return type; } - function getTypeFromStringLiteral(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralType(node); + links.resolvedType = getStringLiteralTypeForText(node.text); } return links.resolvedType; } function getThisType(node) { var container = ts.getThisContainer(node, false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 215)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 217)) { if (!(container.flags & 64) && (container.kind !== 144 || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -15080,6 +15404,22 @@ var ts; } return links.resolvedType; } + function getPredicateType(node) { + return createPredicateType(getSymbolOfNode(node), createTypePredicateFromTypePredicateNode(node)); + } + function createPredicateType(symbol, predicate) { + var type = createType(8 | 134217728); + type.symbol = symbol; + type.predicate = predicate; + return type; + } + function getTypeFromPredicateTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getPredicateType(node); + } + return links.resolvedType; + } function getTypeFromTypeNode(node) { switch (node.kind) { case 117: @@ -15094,15 +15434,15 @@ var ts; return esSymbolType; case 103: return voidType; - case 97: + case 161: return getTypeFromThisTypeNode(node); - case 9: - return getTypeFromStringLiteral(node); + case 162: + return getTypeFromStringLiteralTypeNode(node); case 151: return getTypeFromTypeReference(node); case 150: - return booleanType; - case 188: + return getTypeFromPredicateTypeNode(node); + case 190: return getTypeFromTypeReference(node); case 154: return getTypeFromTypeQueryNode(node); @@ -15180,18 +15520,22 @@ var ts; return t; }; } - function createInferenceMapper(context) { - var mapper = function (t) { - for (var i = 0; i < context.typeParameters.length; i++) { - if (t === context.typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); + function getInferenceMapper(context) { + if (!context.mapper) { + var mapper = function (t) { + var typeParameters = context.typeParameters; + for (var i = 0; i < typeParameters.length; i++) { + if (t === typeParameters[i]) { + context.inferences[i].isFixed = true; + return getInferredType(context, i); + } } - } - return t; - }; - mapper.context = context; - return mapper; + return t; + }; + mapper.context = context; + context.mapper = mapper; + } + return context.mapper; } function identityMapper(type) { return type; @@ -15199,33 +15543,39 @@ var ts; function combineTypeMappers(mapper1, mapper2) { return function (t) { return instantiateType(mapper1(t), mapper2); }; } - function instantiateTypeParameter(typeParameter, mapper) { + function cloneTypeParameter(typeParameter) { var result = createType(512); result.symbol = typeParameter.symbol; - if (typeParameter.constraint) { - result.constraint = instantiateType(typeParameter.constraint, mapper); + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; } else { - result.target = typeParameter; - result.mapper = mapper; + return { + kind: 0, + type: instantiateType(predicate.type, mapper) + }; } - return result; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; - var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } } - if (signature.typePredicate) { - freshTypePredicate = { - parameterName: signature.typePredicate.parameterName, - parameterIndex: signature.typePredicate.parameterIndex, - type: instantiateType(signature.typePredicate.type, mapper) - }; - } - var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -15283,31 +15633,35 @@ var ts; if (type.flags & 32768) { return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); } + if (type.flags & 134217728) { + var predicate = type.predicate; + return createPredicateType(type.symbol, cloneTypePredicate(predicate, mapper)); + } } return type; } function isContextSensitive(node) { ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 173: - case 174: + case 175: + case 176: return isContextSensitiveFunctionLikeDeclaration(node); - case 165: + case 167: return ts.forEach(node.properties, isContextSensitive); - case 164: + case 166: return ts.forEach(node.elements, isContextSensitive); - case 182: + case 184: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 181: + case 183: return node.operatorToken.kind === 52 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 245: + case 247: return isContextSensitive(node.initializer); case 143: case 142: return isContextSensitiveFunctionLikeDeclaration(node); - case 172: + case 174: return isContextSensitive(node.expression); } return false; @@ -15332,7 +15686,7 @@ var ts; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined); } - function compareTypes(source, target) { + function compareTypesIdentical(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined) ? -1 : 0; } function isTypeSubtypeOf(source, target) { @@ -15347,10 +15701,73 @@ var ts; function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } - function isSignatureAssignableTo(source, target) { - var sourceType = getOrCreateTypeFromSignature(source); - var targetType = getOrCreateTypeFromSignature(target); - return checkTypeRelatedTo(sourceType, targetType, assignableRelation, undefined); + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + if (source === target) { + return true; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return false; + } + source = getErasedSignature(source); + target = getErasedSignature(target); + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + for (var i = 0; i < checkCount; i++) { + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + var related = isTypeAssignableTo(t, s) || isTypeAssignableTo(s, t); + if (!related) { + return false; + } + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return true; + } + var sourceReturnType = getReturnTypeOfSignature(source); + if (targetReturnType.flags & 134217728 && targetReturnType.predicate.kind === 1) { + if (!(sourceReturnType.flags & 134217728)) { + return false; + } + } + return isTypeAssignableTo(sourceReturnType, targetReturnType); + } + return true; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, undefined)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; @@ -15405,6 +15822,11 @@ var ts; return -1; if (source.flags & 128 && target === numberType) return -1; + if (source.flags & 128 && target.flags & 128) { + if (result = enumRelatedTo(source, target)) { + return result; + } + } if (source.flags & 256 && target === stringType) return -1; if (relation === assignableRelation) { @@ -15413,6 +15835,36 @@ var ts; if (source === numberType && target.flags & 128) return -1; } + if (source.flags & 8 && target.flags & 8) { + if (source.flags & 134217728 && target.flags & 134217728) { + var sourcePredicate = source; + var targetPredicate = target; + if (sourcePredicate.predicate.kind !== targetPredicate.predicate.kind) { + if (reportErrors) { + reportError(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return 0; + } + if (sourcePredicate.predicate.kind === 1) { + var sourceIdentifierPredicate = sourcePredicate.predicate; + var targetIdentifierPredicate = targetPredicate.predicate; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return 0; + } + } + var related = isRelatedTo(sourcePredicate.predicate.type, targetPredicate.predicate.type, reportErrors, headMessage); + if (related === 0 && reportErrors) { + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return related; + } + return -1; + } if (source.flags & 1048576) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -15488,9 +15940,6 @@ var ts; } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 512 && target.flags & 512) { - return typeParameterIdenticalTo(source, target); - } if (source.flags & 16384 && target.flags & 16384 || source.flags & 32768 && target.flags & 32768) { if (result = eachTypeRelatedToSomeType(source, target)) { @@ -15599,8 +16048,9 @@ var ts; if (sources.length !== targets.length && relation === identityRelation) { return 0; } + var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1; - for (var i = 0; i < targets.length; i++) { + for (var i = 0; i < length; i++) { var related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return 0; @@ -15609,23 +16059,17 @@ var ts; } return result; } - function typeParameterIdenticalTo(source, target) { - if (source.constraint === target.constraint) { - return -1; - } - if (source.constraint === noConstraintType || target.constraint === noConstraintType) { - return 0; - } - return isIdenticalTo(source.constraint, target.constraint); - } - function objectTypeRelatedTo(apparentSource, originalSource, target, reportErrors) { + function objectTypeRelatedTo(source, originalSource, target, reportErrors) { if (overflow) { return 0; } - var id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { - if (!elaborateErrors || (related === 3)) { + if (elaborateErrors && related === 2) { + relation[id] = 3; + } + else { return related === 1 ? -1 : 0; } } @@ -15646,13 +16090,13 @@ var ts; maybeStack = []; expandingFlags = 0; } - sourceStack[depth] = apparentSource; + sourceStack[depth] = source; targetStack[depth] = target; maybeStack[depth] = {}; maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; @@ -15661,15 +16105,15 @@ var ts; result = 1; } else { - result = propertiesRelatedTo(apparentSource, target, reportErrors); + result = propertiesRelatedTo(source, target, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 0, reportErrors); + result &= signaturesRelatedTo(source, target, 0, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 1, reportErrors); + result &= signaturesRelatedTo(source, target, 1, reportErrors); if (result) { - result &= stringIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= stringIndexTypesRelatedTo(source, originalSource, target, reportErrors); if (result) { - result &= numberIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= numberIndexTypesRelatedTo(source, originalSource, target, reportErrors); } } } @@ -15791,61 +16235,38 @@ var ts; } var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 && sourceSignatures.length && targetSignatures.length && + isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0; + } var result = -1; var saveErrorInfo = errorInfo; - if (kind === 1) { - var sourceSig = sourceSignatures[0]; - var targetSig = targetSignatures[0]; - result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); - if (result !== -1) { - return result; - } - } outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; if (!t.hasStringLiterals || target.flags & 262144) { - var localErrors = reportErrors; - var checkedAbstractAssignability = false; + var shouldElaborateErrors = reportErrors; for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { var s = sourceSignatures_1[_a]; if (!s.hasStringLiterals || source.flags & 262144) { - var related = signatureRelatedTo(s, t, localErrors); + var related = signatureRelatedTo(s, t, shouldElaborateErrors); if (related) { result &= related; errorInfo = saveErrorInfo; continue outer; } - localErrors = false; + shouldElaborateErrors = false; } } + if (shouldElaborateErrors && !isPrimitiveApparentType(source)) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } return 0; } } return result; - function abstractSignatureRelatedTo(source, sourceSig, target, targetSig) { - if (sourceSig && targetSig) { - var sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); - var targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); - if (!sourceDecl) { - return -1; - } - var sourceErasedSignature = getErasedSignature(sourceSig); - var targetErasedSignature = getErasedSignature(targetSig); - var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); - var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); - var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); - var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128; - if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0; - } - } - return -1; - } } function signatureRelatedTo(source, target, reportErrors) { if (source === target) { @@ -15893,37 +16314,19 @@ var ts; } result &= related; } - if (source.typePredicate && target.typePredicate) { - var hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; - var hasDifferentTypes; - if (hasDifferentParameterIndex || - (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + if (targetReturnType.flags & 134217728 && targetReturnType.predicate.kind === 1) { + if (!(sourceReturnType.flags & 134217728)) { if (reportErrors) { - var sourceParamText = source.typePredicate.parameterName; - var targetParamText = target.typePredicate.parameterName; - var sourceTypeText = typeToString(source.typePredicate.type); - var targetTypeText = typeToString(target.typePredicate.type); - if (hasDifferentParameterIndex) { - reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceParamText, targetParamText); - } - else if (hasDifferentTypes) { - reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceTypeText, targetTypeText); - } - reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, sourceParamText + " is " + sourceTypeText, targetParamText + " is " + targetTypeText); + reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); } return 0; } } - else if (!source.typePredicate && target.typePredicate) { - if (reportErrors) { - reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); - } - return 0; - } - var targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) - return result; - var sourceReturnType = getReturnTypeOfSignature(source); return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); } function signaturesIdenticalTo(source, target, kind) { @@ -15933,8 +16336,8 @@ var ts; return 0; } var result = -1; - for (var i = 0, len = sourceSignatures.length; i < len; ++i) { - var related = compareSignatures(sourceSignatures[i], targetSignatures[i], false, false, isRelatedTo); + for (var i = 0, len = sourceSignatures.length; i < len; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, isRelatedTo); if (!related) { return 0; } @@ -16014,6 +16417,37 @@ var ts; } return 0; } + function enumRelatedTo(source, target) { + 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)) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + return 0; + } + } + } + return -1; + } + } + function isAbstractConstructorType(type) { + if (type.flags & 65536) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && declaration.flags & 128) { + return true; + } + } + } + return false; } function isDeeplyNestedGeneric(type, stack, depth) { if (type.flags & (4096 | 131072) && depth >= 5) { @@ -16031,7 +16465,7 @@ var ts; return false; } function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypes) !== 0; + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; } function compareProperties(sourceProp, targetProp, compareTypes) { if (sourceProp === targetProp) { @@ -16066,31 +16500,19 @@ var ts; } return false; } - function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + function compareSignaturesIdentical(source, target, partialMatch, ignoreReturnTypes, compareTypes) { if (source === target) { return -1; } if (!(isMatchingSignature(source, target, partialMatch))) { return 0; } - var result = -1; - if (source.typeParameters && target.typeParameters) { - if (source.typeParameters.length !== target.typeParameters.length) { - return 0; - } - for (var i = 0, len = source.typeParameters.length; i < len; ++i) { - var related = compareTypes(source.typeParameters[i], target.typeParameters[i]); - if (!related) { - return 0; - } - result &= related; - } - } - else if (source.typeParameters || target.typeParameters) { + if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) { return 0; } source = getErasedSignature(source); target = getErasedSignature(target); + var result = -1; var targetLen = target.parameters.length; for (var i = 0; i < targetLen; i++) { var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); @@ -16207,10 +16629,13 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); } function getWidenedType(type) { - if (type.flags & 6291456) { + if (type.flags & 140509184) { if (type.flags & (32 | 64)) { return anyType; } + if (type.flags & 134217728) { + return booleanType; + } if (type.flags & 524288) { return getWidenedTypeOfObjectLiteral(type); } @@ -16274,13 +16699,13 @@ var ts; ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 213: + case 215: case 143: case 142: case 145: case 146: - case 173: - case 174: + case 175: + case 176: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -16326,13 +16751,7 @@ var ts; } } function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var unused = typeParameters_1[_i]; - inferences.push({ - primary: undefined, secondary: undefined, isFixed: false - }); - } + var inferences = ts.map(typeParameters, createTypeInferencesObject); return { typeParameters: typeParameters, inferUnionTypes: inferUnionTypes, @@ -16340,6 +16759,13 @@ var ts; inferredTypes: new Array(typeParameters.length) }; } + function createTypeInferencesObject() { + return { + primary: undefined, + secondary: undefined, + isFixed: false + }; + } function inferTypes(context, source, target) { var sourceStack; var targetStack; @@ -16355,6 +16781,21 @@ var ts; return false; } function inferFromTypes(source, target) { + if (source.flags & 16384 && target.flags & 16384 || + source.flags & 32768 && target.flags & 32768) { + var matchingTypes; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (typeIdenticalToSomeType(t, source.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + } + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } if (target.flags & 512) { if (source.flags & 8388608) { return; @@ -16383,6 +16824,11 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } + else if (source.flags & 134217728 && target.flags & 134217728) { + if (source.predicate.kind === target.predicate.kind) { + inferFromTypes(source.predicate.type, target.predicate.type); + } + } else if (source.flags & 8192 && target.flags & 8192 && source.elementTypes.length === target.elementTypes.length) { var sourceTypes = source.elementTypes; var targetTypes = target.elementTypes; @@ -16394,8 +16840,8 @@ var ts; var targetTypes = target.types; var typeParameterCount = 0; var typeParameter; - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var t = targetTypes_2[_i]; + 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)) { typeParameter = t; typeParameterCount++; @@ -16412,15 +16858,16 @@ var ts; } else if (source.flags & 49152) { var sourceTypes = source.types; - for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { - var sourceType = sourceTypes_3[_a]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 && (target.flags & (4096 | 8192) || - (target.flags & 65536) && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { + if (source.flags & 80896 && (target.flags & 4096 && target.typeArguments || + target.flags & 8192 || + target.flags & 65536 && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { if (isInProcess(source, target)) { return; } @@ -16466,14 +16913,7 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - if (source.typePredicate && target.typePredicate) { - if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); - } - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } function inferFromIndexTypes(source, target, sourceKind, targetKind) { var targetIndexType = getIndexTypeOfType(target, targetKind); @@ -16485,6 +16925,25 @@ var ts; } } } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 16384 ? getUnionType(reducedTypes, true) : getIntersectionType(reducedTypes); + } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; @@ -16503,14 +16962,19 @@ var ts; inferredType = emptyObjectType; inferenceSucceeded = true; } + context.inferredTypes[index] = inferredType; if (inferenceSucceeded) { var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); - inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + context.inferredTypes[index] = inferredType = instantiatedConstraint; + } + } } else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { context.failedTypeParameterIndex = index; } - context.inferredTypes[index] = inferredType; } return inferredType; } @@ -16520,9 +16984,6 @@ var ts; } return context.inferredTypes; } - function hasAncestor(node, kind) { - return ts.getAncestor(node, kind) !== undefined; - } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { @@ -16545,21 +17006,6 @@ var ts; } ts.Debug.fail("should not get here"); } - function removeTypesFromUnionType(type, typeKind, isOfTypeKind, allowEmptyUnionResult) { - if (type.flags & 16384) { - var types = type.types; - if (ts.forEach(types, function (t) { return !!(t.flags & typeKind) === isOfTypeKind; })) { - var narrowedType = getUnionType(ts.filter(types, function (t) { return !(t.flags & typeKind) === isOfTypeKind; })); - if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { - return narrowedType; - } - } - } - else if (allowEmptyUnionResult && !!(type.flags & typeKind) === isOfTypeKind) { - return getUnionType(emptyArray); - } - return type; - } function hasInitializer(node) { return !!(node.initializer || ts.isBindingPattern(node.parent) && hasInitializer(node.parent.parent)); } @@ -16577,10 +17023,7 @@ var ts; return links.assignmentChecks[symbol.id] = isAssignedIn(node); function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 56 && node.operatorToken.kind <= 68) { - var n = node.left; - while (n.kind === 172) { - n = n.expression; - } + var n = skipParenthesizedNodes(node.left); if (n.kind === 69 && getResolvedSymbol(n) === symbol) { return true; } @@ -16595,55 +17038,55 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 181: + case 183: return isAssignedInBinaryExpression(node); - case 211: - case 163: - return isAssignedInVariableDeclaration(node); - case 161: - case 162: - case 164: + case 213: case 165: + return isAssignedInVariableDeclaration(node); + case 163: + case 164: case 166: case 167: case 168: case 169: + case 170: case 171: - case 189: - case 172: - case 179: - case 175: - case 178: - case 176: + case 173: + case 191: + case 174: + case 181: case 177: case 180: - case 184: + case 178: + case 179: case 182: - case 185: - case 192: - case 193: + case 186: + case 184: + case 187: + case 194: case 195: - case 196: case 197: case 198: case 199: case 200: case 201: - case 204: - case 205: + case 202: + case 203: case 206: - case 241: - case 242: case 207: case 208: - case 209: + case 243: case 244: - case 233: - case 234: - case 238: - case 239: + case 209: + case 210: + case 211: + case 246: case 235: + case 236: case 240: + case 241: + case 237: + case 242: return ts.forEachChild(node, isAssignedIn); } return false; @@ -16653,53 +17096,66 @@ var ts; var type = getTypeOfSymbol(symbol); if (node && symbol.flags & 3) { if (isTypeAny(type) || type.flags & (80896 | 16384 | 512)) { + var declaration = ts.getDeclarationOfKind(symbol, 213); + var top_1 = declaration && getDeclarationContainer(declaration); + var originalType = type; + var nodeStack = []; loop: while (node.parent) { var child = node; node = node.parent; - var narrowedType = type; switch (node.kind) { - case 196: - if (child !== node.expression) { - narrowedType = narrowType(type, node.expression, child === node.thenStatement); - } + case 198: + case 184: + case 183: + nodeStack.push({ node: node, child: child }); break; - case 182: - if (child !== node.condition) { - narrowedType = narrowType(type, node.condition, child === node.whenTrue); - } - break; - case 181: - if (child === node.right) { - if (node.operatorToken.kind === 51) { - narrowedType = narrowType(type, node.left, true); - } - else if (node.operatorToken.kind === 52) { - narrowedType = narrowType(type, node.left, false); - } - } - break; - case 248: - case 218: - case 213: - case 143: - case 142: - case 145: - case 146: - case 144: + case 250: + case 220: break loop; } - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; - } - type = narrowedType; + if (node === top_1) { + break; } } + var nodes; + while (nodes = nodeStack.pop()) { + var node_1 = nodes.node, child = nodes.child; + switch (node_1.kind) { + case 198: + if (child !== node_1.expression) { + type = narrowType(type, node_1.expression, child === node_1.thenStatement); + } + break; + case 184: + if (child !== node_1.condition) { + type = narrowType(type, node_1.condition, child === node_1.whenTrue); + } + break; + case 183: + if (child === node_1.right) { + if (node_1.operatorToken.kind === 51) { + type = narrowType(type, node_1.left, true); + } + else if (node_1.operatorToken.kind === 52) { + type = narrowType(type, node_1.left, false); + } + } + break; + default: + ts.Debug.fail("Unreachable!"); + } + if (type !== originalType && isVariableAssignedWithin(symbol, node_1)) { + type = originalType; + } + } + if (type === emptyUnionType) { + type = originalType; + } } } return type; function narrowTypeByEquality(type, expr, assumeTrue) { - if (expr.left.kind !== 176 || expr.right.kind !== 9) { + if (expr.left.kind !== 178 || expr.right.kind !== 9) { return type; } var left = expr.left; @@ -16707,24 +17163,30 @@ var ts; if (left.expression.kind !== 69 || getResolvedSymbol(left.expression) !== symbol) { return type; } - var typeInfo = primitiveTypeInfo[right.text]; if (expr.operatorToken.kind === 33) { assumeTrue = !assumeTrue; } - if (assumeTrue) { - if (!typeInfo) { - return removeTypesFromUnionType(type, 258 | 132 | 8 | 16777216, true, false); - } - if (isTypeSubtypeOf(typeInfo.type, type)) { - return typeInfo.type; - } - return removeTypesFromUnionType(type, typeInfo.flags, false, false); + var typeInfo = primitiveTypeInfo[right.text]; + if (typeInfo && typeInfo.type === undefinedType) { + return type; + } + if (!!(type.flags & 1) && typeInfo && assumeTrue) { + return typeInfo.type; + } + var flags; + if (typeInfo) { + flags = typeInfo.flags; } else { - if (typeInfo) { - return removeTypesFromUnionType(type, typeInfo.flags, true, false); - } - return type; + assumeTrue = !assumeTrue; + flags = 132 | 258 | 16777216 | 8; + } + if (!(type.flags & 16384)) { + return filterUnion(type) ? type : emptyUnionType; + } + return getUnionType(ts.filter(type.types, filterUnion), true); + function filterUnion(type) { + return assumeTrue === !!(type.flags & flags); } } function narrowTypeByAnd(type, expr, assumeTrue) { @@ -16734,7 +17196,7 @@ var ts; else { return getUnionType([ narrowType(type, expr.left, false), - narrowType(narrowType(type, expr.left, true), expr.right, false) + narrowType(type, expr.right, false) ]); } } @@ -16742,7 +17204,7 @@ var ts; if (assumeTrue) { return getUnionType([ narrowType(type, expr.left, true), - narrowType(narrowType(type, expr.left, false), expr.right, true) + narrowType(type, expr.right, true) ]); } else { @@ -16778,17 +17240,17 @@ var ts; } } if (targetType) { - if (!assumeTrue) { - if (type.flags & 16384) { - return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, targetType); })); - } - return type; - } - return getNarrowedType(type, targetType); + return getNarrowedType(type, targetType, assumeTrue); } return type; } - function getNarrowedType(originalType, narrowedTypeCandidate) { + function getNarrowedType(originalType, narrowedTypeCandidate, assumeTrue) { + if (!assumeTrue) { + if (originalType.flags & 16384) { + return getUnionType(ts.filter(originalType.types, function (t) { return !isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } if (originalType.flags & 16384) { var assignableConstituents = ts.filter(originalType.types, function (t) { return isTypeAssignableTo(t, narrowedTypeCandidate); }); if (assignableConstituents.length) { @@ -16805,26 +17267,60 @@ var ts; return type; } var signature = getResolvedSignature(expr); - if (signature.typePredicate && - expr.arguments[signature.typePredicate.parameterIndex] && - getSymbolAtLocation(expr.arguments[signature.typePredicate.parameterIndex]) === symbol) { - if (!assumeTrue) { - if (type.flags & 16384) { - return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, signature.typePredicate.type); })); - } - return type; + var predicateType = getReturnTypeOfSignature(signature); + if (!predicateType || !(predicateType.flags & 134217728)) { + return type; + } + var predicate = predicateType.predicate; + if (ts.isIdentifierTypePredicate(predicate)) { + var callExpression = expr; + if (callExpression.arguments[predicate.parameterIndex] && + getSymbolAtTypePredicatePosition(callExpression.arguments[predicate.parameterIndex]) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); } - return getNarrowedType(type, signature.typePredicate.type); + } + else { + var expression = skipParenthesizedNodes(expr.expression); + return narrowTypeByThisTypePredicate(type, predicate, expression, assumeTrue); } return type; } + function narrowTypeByTypePredicateMember(type, expr, assumeTrue) { + if (type.flags & 1) { + return type; + } + var memberType = getTypeOfExpression(expr); + if (!(memberType.flags & 134217728)) { + return type; + } + return narrowTypeByThisTypePredicate(type, memberType.predicate, expr, assumeTrue); + } + function narrowTypeByThisTypePredicate(type, predicate, expression, assumeTrue) { + if (expression.kind === 169 || expression.kind === 168) { + var accessExpression = expression; + var possibleIdentifier = skipParenthesizedNodes(accessExpression.expression); + if (possibleIdentifier.kind === 69 && getSymbolAtTypePredicatePosition(possibleIdentifier) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); + } + } + return type; + } + function getSymbolAtTypePredicatePosition(expr) { + expr = skipParenthesizedNodes(expr); + switch (expr.kind) { + case 69: + case 168: + case 135: + return getSymbolOfEntityNameOrPropertyAccessExpression(expr); + } + } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 168: + case 170: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 172: + case 174: return narrowType(type, expr.expression, assumeTrue); - case 181: + case 183: var operator = expr.operatorToken.kind; if (operator === 32 || operator === 33) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -16839,20 +17335,29 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 179: + case 181: if (expr.operator === 49) { return narrowType(type, expr.operand, !assumeTrue); } break; + case 169: + case 168: + return narrowTypeByTypePredicateMember(type, expr, assumeTrue); } return type; } } + function skipParenthesizedNodes(expression) { + while (expression.kind === 174) { + expression = expression.expression; + } + return expression; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 174) { + if (container.kind === 176) { if (languageVersion < 2) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } @@ -16883,7 +17388,7 @@ var ts; function checkBlockScopedBindingCapturedInLoop(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 244) { + symbol.valueDeclaration.parent.kind === 246) { return; } var container; @@ -16892,11 +17397,11 @@ var ts; } else { container = symbol.valueDeclaration; - while (container.kind !== 212) { + while (container.kind !== 214) { container = container.parent; } container = container.parent; - if (container.kind === 193) { + if (container.kind === 195) { container = container.parent; } } @@ -16926,15 +17431,15 @@ var ts; function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; - if (container.kind === 174) { + if (container.kind === 176) { container = ts.getThisContainer(container, false); needToCaptureLexicalThis = (languageVersion < 2); } switch (container.kind) { - case 218: + case 220: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 217: + case 219: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; case 144: @@ -16959,6 +17464,18 @@ var ts; var symbol = getSymbolOfNode(container.parent); return container.flags & 64 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; } + if (ts.isInJavaScriptFile(node) && container.kind === 175) { + if (ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { + var className = container.parent + .left + .expression + .expression; + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { + return getInferredClassType(classSymbol); + } + } + } return anyType; } function isInConstructorArgumentInitializer(node, constructorDecl) { @@ -16970,50 +17487,64 @@ var ts; return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 168 && node.parent.expression === node; - var classDeclaration = ts.getContainingClass(node); - var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; + var isCallExpression = node.parent.kind === 170 && node.parent.expression === node; var container = ts.getSuperContainer(node, true); var needToCaptureLexicalThis = false; if (!isCallExpression) { - while (container && container.kind === 174) { + while (container && container.kind === 176) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; - if (canUseSuperExpression) { - if ((container.flags & 64) || isCallExpression) { - nodeCheckFlag = 512; - } - else { - nodeCheckFlag = 256; - } - getNodeLinks(node).flags |= nodeCheckFlag; - if (needToCaptureLexicalThis) { - captureLexicalThis(node.parent, container); - } - } - if (!baseClassType) { - if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } if (!canUseSuperExpression) { - if (container && container.kind === 136) { + var current = node; + while (current && current !== container && current.kind !== 136) { + current = current.parent; + } + if (current && current.kind === 136) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 167)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } else { error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); } return unknownType; } + if ((container.flags & 64) || isCallExpression) { + nodeCheckFlag = 512; + } + else { + nodeCheckFlag = 256; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (needToCaptureLexicalThis) { + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 167) { + if (languageVersion < 2) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + return anyType; + } + } + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } if (container.kind === 144 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; @@ -17029,7 +17560,7 @@ var ts; return container.kind === 144; } else { - if (container && ts.isClassLike(container.parent)) { + if (ts.isClassLike(container.parent) || container.parent.kind === 167) { if (container.flags & 64) { return container.kind === 143 || container.kind === 142 || @@ -17140,7 +17671,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 170) { + if (template.parent.kind === 172) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -17160,6 +17691,11 @@ var ts; } return type; } + else if (operator === 51 || operator === 24) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } return undefined; } function applyToContextualType(type, mapper) { @@ -17169,8 +17705,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var current = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -17242,21 +17778,20 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForJsxExpression(expr) { - if (expr.parent.kind === 238) { - var attrib = expr.parent; - var attrsType = getJsxElementAttributesType(attrib.parent); + function getContextualTypeForJsxAttribute(attribute) { + var kind = attribute.kind; + var jsxElement = attribute.parent; + var attrsType = getJsxElementAttributesType(jsxElement); + if (attribute.kind === 240) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } - else { - return getTypeOfPropertyOfType(attrsType, attrib.name.text); - } + return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - if (expr.kind === 239) { - return getJsxElementAttributesType(expr.parent); + else if (attribute.kind === 241) { + return attrsType; } - return undefined; + ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); } function getApparentTypeOfContextualType(node) { var type = getContextualType(node); @@ -17271,39 +17806,41 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 211: + case 213: case 138: case 141: case 140: - case 163: + case 165: return getContextualTypeForInitializerExpression(node); - case 174: - case 204: + case 176: + case 206: return getContextualTypeForReturnExpression(node); - case 184: + case 186: return getContextualTypeForYieldOperand(parent); - case 168: - case 169: - return getContextualTypeForArgument(parent, node); + case 170: case 171: - case 189: + return getContextualTypeForArgument(parent, node); + case 173: + case 191: return getTypeFromTypeNode(parent.type); - case 181: + case 183: return getContextualTypeForBinaryOperand(node); - case 245: + case 247: return getContextualTypeForObjectLiteralElement(parent); - case 164: + case 166: return getContextualTypeForElementExpression(node); - case 182: + case 184: return getContextualTypeForConditionalOperand(node); - case 190: - ts.Debug.assert(parent.parent.kind === 183); + case 192: + ts.Debug.assert(parent.parent.kind === 185); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 172: + case 174: + return getContextualType(parent); + case 242: return getContextualType(parent); case 240: - case 239: - return getContextualTypeForJsxExpression(parent); + case 241: + return getContextualTypeForJsxAttribute(parent); } return undefined; } @@ -17317,7 +17854,7 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 173 || node.kind === 174; + return node.kind === 175 || node.kind === 176; } function getContextualSignatureForFunctionLikeDeclaration(node) { return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) @@ -17337,14 +17874,14 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { signatureList = [signature]; } - else if (!compareSignatures(signatureList[0], signature, false, true, compareTypes)) { + else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, compareTypesIdentical)) { return undefined; } else { @@ -17365,13 +17902,13 @@ var ts; } function isAssignmentTarget(node) { var parent = node.parent; - if (parent.kind === 181 && parent.operatorToken.kind === 56 && parent.left === node) { + if (parent.kind === 183 && parent.operatorToken.kind === 56 && parent.left === node) { return true; } - if (parent.kind === 245) { + if (parent.kind === 247) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 164) { + if (parent.kind === 166) { return isAssignmentTarget(parent); } return false; @@ -17381,8 +17918,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false); } function hasDefaultValue(node) { - return (node.kind === 163 && !!node.initializer) || - (node.kind === 181 && node.operatorToken.kind === 56); + return (node.kind === 165 && !!node.initializer) || + (node.kind === 183 && node.operatorToken.kind === 56); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -17391,7 +17928,7 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 185) { + if (inDestructuringPattern && e.kind === 187) { var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1) || (languageVersion >= 2 ? getElementTypeOfIterable(restArrayType, undefined) : undefined); @@ -17403,7 +17940,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 185; + hasSpreadElement = hasSpreadElement || e.kind === 187; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { @@ -17414,7 +17951,7 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { var pattern = contextualType.pattern; - if (pattern && (pattern.kind === 162 || pattern.kind === 164)) { + if (pattern && (pattern.kind === 164 || pattern.kind === 166)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -17422,7 +17959,7 @@ var ts; elementTypes.push(contextualType.elementTypes[i]); } else { - if (patternElement.kind !== 187) { + if (patternElement.kind !== 189) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -17468,31 +18005,31 @@ var ts; var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 161 || contextualType.pattern.kind === 165); + (contextualType.pattern.kind === 163 || contextualType.pattern.kind === 167); var typeFlags = 0; var patternWithComputedProperties = false; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 245 || - memberDecl.kind === 246 || + if (memberDecl.kind === 247 || + memberDecl.kind === 248 || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 245) { + if (memberDecl.kind === 247) { type = checkPropertyAssignment(memberDecl, contextualMapper); } else if (memberDecl.kind === 143) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 246); + ts.Debug.assert(memberDecl.kind === 248); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 | 67108864 | member.flags, member.name); if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 245 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 246 && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 247 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 248 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912; } @@ -17571,34 +18108,19 @@ var ts; checkJsxOpeningLikeElement(node); return jsxElementType || anyType; } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 69) { - return lhs.text === rhs.text; - } - return lhs.right.text === rhs.right.text && - tagNamesAreEquivalent(lhs.left, rhs.left); - } function checkJsxElement(node) { checkJsxOpeningLikeElement(node.openingElement); - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - error(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNode(node.openingElement.tagName)); - } - else { - getJsxElementTagSymbol(node.closingElement); - } + getJsxElementTagSymbol(node.closingElement); for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 240: + case 242: checkJsxExpression(child); break; - case 233: + case 235: checkJsxElement(child); break; - case 234: + case 236: checkJsxSelfClosingElement(child); break; } @@ -17666,14 +18188,13 @@ var ts; } return type; } - function getJsxIntrinsicElementsType() { - if (!jsxIntrinsicElementsType) { - jsxIntrinsicElementsType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.IntrinsicElements) || unknownType; + function getJsxType(name) { + if (jsxTypes[name] === undefined) { + return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType; } - return jsxIntrinsicElementsType; + return jsxTypes[name]; } function getJsxElementTagSymbol(node) { - var flags = 8; var links = getNodeLinks(node); if (!links.resolvedSymbol) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -17685,7 +18206,7 @@ var ts; } return links.resolvedSymbol; function lookupIntrinsicTag(node) { - var intrinsicElementsType = getJsxIntrinsicElementsType(); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); if (intrinsicProp) { @@ -17745,12 +18266,7 @@ var ts; return unknownType; } } - var returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); - var elemClassType = getJsxGlobalElementClassType(); - if (elemClassType) { - checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - return returnType; + return getUnionType(signatures.map(getReturnTypeOfSignature)); } function getJsxElementPropertiesName() { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536, undefined); @@ -17779,6 +18295,20 @@ var ts; var sym = getJsxElementTagSymbol(node); if (links.jsxFlags & 4) { var elemInstanceType = getJsxElementInstanceType(node); + var callSignature = getSingleCallSignature(getTypeOfSymbol(sym)); + var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); + var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType) && (paramType.flags & 80896)) { + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return paramType; + } + var elemClassType = getJsxGlobalElementClassType(); + if (elemClassType) { + checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } @@ -17797,12 +18327,29 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return links.resolvedJsxType = attributesType; } - else if (!(attributesType.flags & 80896)) { - error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_must_be_an_object_type, typeToString(attributesType)); + else if (attributesType.flags & 16384) { + error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return links.resolvedJsxType = anyType; } else { - return links.resolvedJsxType = attributesType; + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return links.resolvedJsxType = apparentAttributesType; } } } @@ -17830,7 +18377,7 @@ var ts; return jsxElementClassType; } function getJsxIntrinsicTagNames() { - var intrinsics = getJsxIntrinsicElementsType(); + var intrinsics = getJsxType(JsxNames.IntrinsicElements); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } function checkJsxPreconditions(errorNode) { @@ -17846,21 +18393,21 @@ var ts; function checkJsxOpeningLikeElement(node) { checkGrammarJsxElement(node); checkJsxPreconditions(node); - if (compilerOptions.jsx === 2) { - var reactSym = resolveName(node.tagName, "React", 107455, ts.Diagnostics.Cannot_find_name_0, "React"); - if (reactSym) { - getSymbolLinks(reactSym).referenced = true; - } + var reactRefErr = compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); + if (reactSym) { + getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = {}; var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 238) { + if (node.attributes[i].kind === 240) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 239); + ts.Debug.assert(node.attributes[i].kind === 241); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -17895,10 +18442,10 @@ var ts; var flags = getDeclarationFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (left.kind === 95) { - var errorNode = node.kind === 166 ? + var errorNode = node.kind === 168 ? node.name : node.right; - if (getDeclarationKindFromSymbol(prop) !== 143) { + if (languageVersion < 2 && getDeclarationKindFromSymbol(prop) !== 143) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } @@ -17967,7 +18514,7 @@ var ts; return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 166 + var left = node.kind === 168 ? node.expression : node.left; var type = checkExpression(left); @@ -17982,7 +18529,7 @@ var ts; function checkIndexedAccess(node) { if (!node.argumentExpression) { var sourceFile = getSourceFile(node); - if (node.parent.kind === 169 && node.parent.expression === node) { + if (node.parent.kind === 171 && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -18005,15 +18552,15 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_12 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_12 !== undefined) { - var prop = getPropertyOfType(objectType, name_12); + var name_11 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_11 !== undefined) { + var prop = getPropertyOfType(objectType, name_11); 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_12, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_11, symbolToString(objectType.symbol)); return unknownType; } } @@ -18041,7 +18588,7 @@ var ts; if (indexArgumentExpression.kind === 9 || indexArgumentExpression.kind === 8) { return indexArgumentExpression.text; } - if (indexArgumentExpression.kind === 167 || indexArgumentExpression.kind === 166) { + if (indexArgumentExpression.kind === 169 || indexArgumentExpression.kind === 168) { var value = getConstantValue(indexArgumentExpression); if (value !== undefined) { return value.toString(); @@ -18084,7 +18631,7 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 170) { + if (node.kind === 172) { checkExpression(node.template); } else if (node.kind !== 139) { @@ -18138,7 +18685,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 185) { + if (arg && arg.kind === 187) { return i; } } @@ -18150,11 +18697,11 @@ var ts; var callIsIncomplete; var isDecorator; var spreadArgIndex = -1; - if (node.kind === 170) { + if (node.kind === 172) { var tagExpression = node; adjustedArgCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 183) { + if (tagExpression.template.kind === 185) { var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -18174,7 +18721,7 @@ var ts; else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 169); + ts.Debug.assert(callExpression.kind === 171); return signature.minArgumentCount === 0; } adjustedArgCount = callExpression.arguments.hasTrailingComma ? args.length + 1 : args.length; @@ -18215,7 +18762,7 @@ var ts; } function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; - var inferenceMapper = createInferenceMapper(context); + var inferenceMapper = getInferenceMapper(context); for (var i = 0; i < typeParameters.length; i++) { if (!context.inferences[i].isFixed) { context.inferredTypes[i] = undefined; @@ -18227,7 +18774,7 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 187) { + if (arg === undefined || arg.kind !== 189) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { @@ -18248,13 +18795,11 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; + var mapper; for (var i = 0; i < typeParameters.length; i++) { - var typeArgNode = typeArguments[i]; - var typeArgument = getTypeFromTypeNode(typeArgNode); - typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { @@ -18264,7 +18809,11 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); typeArgumentHeadMessage = headMessage; } - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); } } } @@ -18274,12 +18823,12 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 187) { + if (arg === undefined || arg.kind !== 189) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { argType = arg.kind === 9 && !reportErrors - ? getStringLiteralType(arg) + ? getStringLiteralTypeForText(arg.text) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; @@ -18293,10 +18842,10 @@ var ts; } function getEffectiveCallArguments(node) { var args; - if (node.kind === 170) { + if (node.kind === 172) { var template = node.template; args = [undefined]; - if (template.kind === 183) { + if (template.kind === 185) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); @@ -18313,8 +18862,8 @@ var ts; function getEffectiveArgumentCount(node, args, signature) { if (node.kind === 139) { switch (node.parent.kind) { - case 214: - case 186: + case 216: + case 188: return 1; case 141: return 2; @@ -18334,7 +18883,7 @@ var ts; } } function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 216) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } @@ -18355,7 +18904,7 @@ var ts; return unknownType; } function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 216) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } @@ -18374,7 +18923,7 @@ var ts; case 69: case 8: case 9: - return getStringLiteralType(element.name); + return getStringLiteralTypeForText(element.name.text); case 136: var nameType = checkComputedPropertyName(element.name); if (allConstituentTypesHaveKind(nameType, 16777216)) { @@ -18392,7 +18941,7 @@ var ts; return unknownType; } function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 216) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } @@ -18429,14 +18978,14 @@ var ts; if (node.kind === 139) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 170) { + else if (argIndex === 0 && node.kind === 172) { return globalTemplateStringsArrayType; } return undefined; } function getEffectiveArgument(node, args, argIndex) { if (node.kind === 139 || - (argIndex === 0 && node.kind === 170)) { + (argIndex === 0 && node.kind === 172)) { return undefined; } return args[argIndex]; @@ -18445,7 +18994,7 @@ var ts; if (node.kind === 139) { return node.expression; } - else if (argIndex === 0 && node.kind === 170) { + else if (argIndex === 0 && node.kind === 172) { return node.template; } else { @@ -18453,7 +19002,7 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 170; + var isTaggedTemplate = node.kind === 172; var isDecorator = node.kind === 139; var typeArguments; if (!isTaggedTemplate && !isDecorator) { @@ -18501,7 +19050,8 @@ var ts; } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true, headMessage); + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -18553,7 +19103,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { @@ -18685,8 +19235,8 @@ var ts; } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 214: - case 186: + case 216: + case 188: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; case 138: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; @@ -18722,13 +19272,13 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 168) { + if (node.kind === 170) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 169) { + else if (node.kind === 171) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 170) { + else if (node.kind === 172) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } else if (node.kind === 139) { @@ -18740,19 +19290,30 @@ var ts; } return links.resolvedSignature; } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined); + } + return links.inferredClassType; + } function checkCallExpression(node) { checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 95) { return voidType; } - if (node.kind === 169) { + if (node.kind === 171) { var declaration = signature.declaration; if (declaration && declaration.kind !== 144 && declaration.kind !== 148 && declaration.kind !== 153) { - if (compilerOptions.noImplicitAny) { + var funcSymbol = checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16)) { + return getInferredClassType(funcSymbol); + } + else if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; @@ -18801,7 +19362,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187) { + if (element.kind !== 189) { if (element.name.kind === 69) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -18835,7 +19396,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 192) { + if (func.body.kind !== 194) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -18940,22 +19501,29 @@ var ts; if (returnType === voidType || isTypeAny(returnType)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 || !(func.flags & 524288)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 194 || !(func.flags & 524288)) { return; } - if (func.flags & 1048576) { - if (compilerOptions.noImplicitReturns) { - error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { + var hasExplicitReturn = func.flags & 1048576; + if (returnType && !hasExplicitReturn) { error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + var inferredReturnType = hasExplicitReturn + ? getReturnTypeOfSignature(getSignatureFromDeclaration(func)) + : voidType; + if (inferredReturnType === voidType || isTypeAny(inferredReturnType)) { + return; + } + } + error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 173) { + if (!hasGrammarError && node.kind === 175) { checkGrammarForGenerator(node); } if (contextualMapper === identityMapper && isContextSensitive(node)) { @@ -18988,6 +19556,7 @@ var ts; } if (!contextChecked) { checkSignatureDeclaration(node); + checkNodeDeferred(node); } } } @@ -18997,39 +19566,34 @@ var ts; } return type; } - function checkFunctionExpressionOrObjectLiteralMethodBody(node) { + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; } - var returnType = node.type && getTypeFromTypeNode(node.type); - var promisedType; - if (returnType && isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - if (returnType && !node.asteriskToken) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + if (!node.asteriskToken) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { if (!node.type) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 192) { + if (node.body.kind === 194) { checkSourceElement(node.body); } else { var exprType = checkExpression(node.body); - if (returnType) { + if (returnOrPromisedType) { if (isAsync) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); - checkTypeAssignableTo(awaitedType, promisedType, node.body); + checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } else { - checkTypeAssignableTo(exprType, returnType, node.body); + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } - checkFunctionAndClassExpressionBodies(node.body); } } } @@ -19051,13 +19615,13 @@ var ts; var symbol = findSymbol(n); return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 3) !== 0; } - case 166: { + case 168: { var symbol = findSymbol(n); return !symbol || symbol === unknownSymbol || (symbol.flags & ~8) !== 0; } - case 167: + case 169: return true; - case 172: + case 174: return isReferenceOrErrorExpression(n.expression); default: return false; @@ -19066,21 +19630,21 @@ var ts; function isConstVariableReference(n) { switch (n.kind) { case 69: - case 166: { + case 168: { var symbol = findSymbol(n); return symbol && (symbol.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384) !== 0; } - case 167: { + case 169: { var index = n.argumentExpression; var symbol = findSymbol(n.expression); if (symbol && index && index.kind === 9) { - var name_13 = index.text; - var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_13); + var name_12 = index.text; + var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_12); return prop && (prop.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 16384) !== 0; } return false; } - case 172: + case 174: return isConstVariableReference(n.expression); default: return false; @@ -19156,8 +19720,8 @@ var ts; } if (type.flags & 49152) { 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_10 = types; _i < types_10.length; _i++) { + var current = types_10[_i]; if (current.flags & kind) { return true; } @@ -19172,8 +19736,8 @@ var ts; } if (type.flags & 49152) { var types = type.types; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var current = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var current = types_11[_i]; if (!(current.flags & kind)) { return false; } @@ -19210,22 +19774,22 @@ var ts; var properties = node.properties; for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var p = properties_3[_i]; - if (p.kind === 245 || p.kind === 246) { - var name_14 = p.name; - if (name_14.kind === 136) { - checkComputedPropertyName(name_14); + if (p.kind === 247 || p.kind === 248) { + var name_13 = p.name; + if (name_13.kind === 136) { + checkComputedPropertyName(name_13); } - if (isComputedNonLiteralName(name_14)) { + if (isComputedNonLiteralName(name_13)) { continue; } - var text = getTextOfPropertyName(name_14); + var text = getTextOfPropertyName(name_13); var type = isTypeAny(sourceType) ? sourceType : getTypeOfPropertyOfType(sourceType, text) || isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1) || getIndexTypeOfType(sourceType, 0); if (type) { - if (p.kind === 246) { + if (p.kind === 248) { checkDestructuringAssignment(p, type); } else { @@ -19233,7 +19797,7 @@ var ts; } } else { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_14)); + error(name_13, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_13)); } } else { @@ -19247,8 +19811,8 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187) { - if (e.kind !== 185) { + if (e.kind !== 189) { + if (e.kind !== 187) { var propName = "" + i; var type = isTypeAny(sourceType) ? sourceType @@ -19273,7 +19837,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 181 && restExpression.operatorToken.kind === 56) { + if (restExpression.kind === 183 && restExpression.operatorToken.kind === 56) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -19287,7 +19851,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 246) { + if (exprOrAssignment.kind === 248) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -19297,14 +19861,14 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 181 && target.operatorToken.kind === 56) { + if (target.kind === 183 && target.operatorToken.kind === 56) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 165) { + if (target.kind === 167) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 164) { + if (target.kind === 166) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); @@ -19321,7 +19885,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 && (left.kind === 165 || left.kind === 164)) { + if (operator === 56 && (left.kind === 167 || left.kind === 166)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); @@ -19520,7 +20084,7 @@ var ts; function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { - return getStringLiteralType(node); + return getStringLiteralTypeForText(node.text); } return stringType; } @@ -19583,8 +20147,8 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 166 && node.parent.expression === node) || - (node.parent.kind === 167 && node.parent.expression === node) || + var ok = (node.parent.kind === 168 && node.parent.expression === node) || + (node.parent.kind === 169 && node.parent.expression === node) || ((node.kind === 69 || node.kind === 135) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); @@ -19611,7 +20175,7 @@ var ts; return booleanType; case 8: return checkNumericLiteral(node); - case 183: + case 185: return checkTemplateExpression(node); case 9: return checkStringLiteralExpression(node); @@ -19619,58 +20183,58 @@ var ts; return stringType; case 10: return globalRegExpType; - case 164: - return checkArrayLiteral(node, contextualMapper); - case 165: - return checkObjectLiteral(node, contextualMapper); case 166: - return checkPropertyAccessExpression(node); + return checkArrayLiteral(node, contextualMapper); case 167: - return checkIndexedAccess(node); + return checkObjectLiteral(node, contextualMapper); case 168: + return checkPropertyAccessExpression(node); case 169: - return checkCallExpression(node); + return checkIndexedAccess(node); case 170: - return checkTaggedTemplateExpression(node); - case 172: - return checkExpression(node.expression, contextualMapper); - case 186: - return checkClassExpression(node); - case 173: - case 174: - return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 176: - return checkTypeOfExpression(node); case 171: - case 189: - return checkAssertion(node); + return checkCallExpression(node); + case 172: + return checkTaggedTemplateExpression(node); + case 174: + return checkExpression(node.expression, contextualMapper); + case 188: + return checkClassExpression(node); case 175: - return checkDeleteExpression(node); - case 177: - return checkVoidExpression(node); + case 176: + return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); case 178: - return checkAwaitExpression(node); + return checkTypeOfExpression(node); + case 173: + case 191: + return checkAssertion(node); + case 177: + return checkDeleteExpression(node); case 179: - return checkPrefixUnaryExpression(node); + return checkVoidExpression(node); case 180: - return checkPostfixUnaryExpression(node); + return checkAwaitExpression(node); case 181: - return checkBinaryExpression(node, contextualMapper); + return checkPrefixUnaryExpression(node); case 182: - return checkConditionalExpression(node, contextualMapper); - case 185: - return checkSpreadElementExpression(node, contextualMapper); - case 187: - return undefinedType; + return checkPostfixUnaryExpression(node); + case 183: + return checkBinaryExpression(node, contextualMapper); case 184: + return checkConditionalExpression(node, contextualMapper); + case 187: + return checkSpreadElementExpression(node, contextualMapper); + case 189: + return undefinedType; + case 186: return checkYieldExpression(node); - case 240: + case 242: return checkJsxExpression(node); - case 233: - return checkJsxElement(node); - case 234: - return checkJsxSelfClosingElement(node); case 235: + return checkJsxElement(node); + case 236: + return checkJsxSelfClosingElement(node); + case 237: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -19680,8 +20244,8 @@ var ts; grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } checkSourceElement(node.constraint); + getConstraintOfTypeParameter(getDeclaredTypeOfTypeParameter(getSymbolOfNode(node))); if (produceDiagnostics) { - checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } @@ -19707,8 +20271,8 @@ var ts; return false; } return node.kind === 143 || - node.kind === 213 || - node.kind === 173; + node.kind === 215 || + node.kind === 175; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { @@ -19722,12 +20286,12 @@ var ts; } return -1; } - function isInLegalTypePredicatePosition(node) { + function isInLegalParameterTypePredicatePosition(node) { switch (node.parent.kind) { - case 174: + case 176: case 147: - case 213: - case 173: + case 215: + case 175: case 152: case 143: case 142: @@ -19735,11 +20299,23 @@ var ts; } return false; } + function isInLegalThisTypePredicatePosition(node) { + if (isInLegalParameterTypePredicatePosition(node)) { + return true; + } + switch (node.parent.kind) { + case 141: + case 140: + case 145: + return node === node.parent.type; + } + return false; + } function checkSignatureDeclaration(node) { if (node.kind === 149) { checkGrammarIndexSignature(node); } - else if (node.kind === 152 || node.kind === 213 || node.kind === 153 || + else if (node.kind === 152 || node.kind === 215 || node.kind === 153 || node.kind === 147 || node.kind === 144 || node.kind === 148) { checkGrammarFunctionLikeDeclaration(node); @@ -19748,9 +20324,14 @@ var ts; ts.forEach(node.parameters, checkParameter); if (node.type) { if (node.type.kind === 150) { - var typePredicate = getSignatureFromDeclaration(node).typePredicate; + var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + if (!returnType || !(returnType.flags & 134217728)) { + return; + } + var typePredicate = returnType.predicate; var typePredicateNode = node.type; - if (isInLegalTypePredicatePosition(typePredicateNode)) { + checkSourceElement(typePredicateNode); + if (ts.isIdentifierTypePredicate(typePredicate)) { if (typePredicate.parameterIndex >= 0) { if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); @@ -19766,8 +20347,8 @@ var ts; if (hasReportedError) { break; } - if (param.name.kind === 161 || - param.name.kind === 162) { + if (param.name.kind === 163 || + param.name.kind === 164) { (function checkBindingPattern(pattern) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; @@ -19777,8 +20358,8 @@ var ts; hasReportedError = true; break; } - else if (element.name.kind === 162 || - element.name.kind === 161) { + else if (element.name.kind === 164 || + element.name.kind === 163) { checkBindingPattern(element.name); } } @@ -19790,9 +20371,6 @@ var ts; } } } - else { - error(typePredicateNode, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); - } } else { checkSourceElement(node.type); @@ -19827,7 +20405,7 @@ var ts; checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 215) { + if (node.kind === 217) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -19869,7 +20447,7 @@ var ts; } function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); - checkFunctionLikeDeclaration(node); + checkFunctionOrMethodDeclaration(node); if (node.flags & 128 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } @@ -19890,7 +20468,7 @@ var ts; return; } function isSuperCallExpression(n) { - return n.kind === 168 && n.expression.kind === 95; + return n.kind === 170 && n.expression.kind === 95; } function containsSuperCallAsComputedPropertyName(n) { return n.name && containsSuperCall(n.name); @@ -19911,7 +20489,7 @@ var ts; if (n.kind === 97) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 173 && n.kind !== 213) { + else if (n.kind !== 175 && n.kind !== 215) { ts.forEachChild(n, markThisReferencesAsErrors); } } @@ -19936,7 +20514,7 @@ var ts; var superCallStatement; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 195 && isSuperCallExpression(statement.expression)) { + if (statement.kind === 197 && isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; } @@ -19960,6 +20538,8 @@ var ts; function checkAccessorDeclaration(node) { if (produceDiagnostics) { checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); if (node.kind === 145) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288)) { if (node.flags & 1048576) { @@ -19972,6 +20552,9 @@ var ts; } } } + if (node.name.kind === 136) { + checkComputedPropertyName(node.name); + } if (!ts.hasDynamicName(node)) { var otherKind = node.kind === 145 ? 146 : 145; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); @@ -19990,18 +20573,32 @@ var ts; } getTypeOfAccessors(getSymbolOfNode(node)); } - checkFunctionLikeDeclaration(node); + if (node.parent.kind !== 167) { + checkSourceElement(node.body); + } + else { + checkNodeDeferred(node); + } + } + function checkAccessorDeferred(node) { + checkSourceElement(node.body); } function checkMissingDeclaration(node) { checkDecorators(node); } - function checkTypeArgumentConstraints(typeParameters, typeArguments) { + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var typeArguments; + var mapper; var result = true; for (var i = 0; i < typeParameters.length; i++) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { + if (!typeArguments) { + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + mapper = createTypeMapper(typeParameters, typeArguments); + } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; @@ -20058,7 +20655,7 @@ var ts; return; } var signaturesToCheck; - if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 215) { + if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 217) { ts.Debug.assert(signatureDeclarationNode.kind === 147 || signatureDeclarationNode.kind === 148); var signatureKind = signatureDeclarationNode.kind === 147 ? 0 : 1; var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); @@ -20070,7 +20667,7 @@ var ts; } for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { var otherSignature = signaturesToCheck_1[_i]; - if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { + if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature, false)) { return; } } @@ -20078,9 +20675,9 @@ var ts; } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedNodeFlags(n); - if (n.parent.kind !== 215 && - n.parent.kind !== 214 && - n.parent.kind !== 186 && + if (n.parent.kind !== 217 && + n.parent.kind !== 216 && + n.parent.kind !== 188 && ts.isInAmbientContext(n)) { if (!(flags & 4)) { flags |= 2; @@ -20153,14 +20750,16 @@ var ts; seen = c === node; } }); - if (subsequentNode) { + if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - ts.Debug.assert(node.kind === 143 || node.kind === 142); - ts.Debug.assert((node.flags & 64) !== (subsequentNode.flags & 64)); - var diagnostic = node.flags & 64 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); + var reportError = (node.kind === 143 || node.kind === 142) && + (node.flags & 64) !== (subsequentNode.flags & 64); + if (reportError) { + var diagnostic = node.flags & 64 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } return; } else if (ts.nodeIsPresent(subsequentNode.body)) { @@ -20189,11 +20788,11 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 215 || node.parent.kind === 155 || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 217 || node.parent.kind === 155 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 213 || node.kind === 143 || node.kind === 142 || node.kind === 144) { + if (node.kind === 215 || node.kind === 143 || node.kind === 142 || node.kind === 144) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -20247,7 +20846,7 @@ var ts; if (!bodySignature.hasStringLiterals) { for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { var signature = signatures_3[_a]; - if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { + if (!signature.hasStringLiterals && !isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; } @@ -20306,16 +20905,16 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 215: + case 217: return 2097152; - case 218: + case 220: return d.name.kind === 9 || ts.getModuleInstanceState(d) !== 0 ? 4194304 | 1048576 : 4194304; - case 214: - case 217: + case 216: + case 219: return 2097152 | 1048576; - case 221: + case 223: var result = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); @@ -20422,15 +21021,16 @@ var ts; error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } + checkReturnTypeAnnotationAsExpression(node); var promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } var promiseName = ts.getEntityNameFromTypeNode(node.type); - var root = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, root.text, 107455); + var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); + var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455); if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, getFullyQualifiedName(promiseConstructor)); + error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); return unknownType; } return checkAwaitedType(promiseType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); @@ -20445,7 +21045,7 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 214: + case 216: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); @@ -20482,23 +21082,10 @@ var ts; } } function checkTypeAnnotationAsExpression(node) { - switch (node.kind) { - case 141: - checkTypeNodeAsExpression(node.type); - break; - case 138: - checkTypeNodeAsExpression(node.type); - break; - case 143: - checkTypeNodeAsExpression(node.type); - break; - case 145: - checkTypeNodeAsExpression(node.type); - break; - case 146: - checkTypeNodeAsExpression(ts.getSetAccessorTypeAnnotationNode(node)); - break; - } + checkTypeNodeAsExpression(node.type); + } + function checkReturnTypeAnnotationAsExpression(node) { + checkTypeNodeAsExpression(node.type); } function checkParameterTypeAnnotationsAsExpressions(node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -20518,16 +21105,18 @@ var ts; } if (compilerOptions.emitDecoratorMetadata) { switch (node.kind) { - case 214: + case 216: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; case 143: - checkParameterTypeAnnotationsAsExpressions(node); - case 146: case 145: + case 146: + checkParameterTypeAnnotationsAsExpressions(node); + checkReturnTypeAnnotationAsExpression(node); + break; case 141: case 138: checkTypeAnnotationAsExpression(node); @@ -20542,13 +21131,13 @@ var ts; } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); + checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); } } - function checkFunctionLikeDeclaration(node) { + function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); var isAsync = ts.isAsyncFunctionLike(node); @@ -20561,7 +21150,8 @@ var ts; if (!ts.hasDynamicName(node)) { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.getDeclarationOfKind(localSymbol, node.kind); + var firstDeclaration = ts.forEach(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(getSourceFile(declaration)) ? + declaration : undefined; }); if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); } @@ -20572,13 +21162,9 @@ var ts; } } checkSourceElement(node.body); - if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { - var returnType = getTypeFromTypeNode(node.type); - var promisedType; - if (isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + if (!node.asteriskToken) { + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !node.type) { if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { @@ -20590,13 +21176,10 @@ var ts; } } function checkBlock(node) { - if (node.kind === 192) { + if (node.kind === 194) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 219) { - checkFunctionAndClassExpressionBodies(node); - } } function checkCollisionWithArgumentsInGeneratedCode(node) { if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { @@ -20672,11 +21255,11 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 218 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 220 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 248 && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 250 && ts.isExternalOrCommonJsModule(parent)) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -20684,7 +21267,7 @@ var ts; if ((ts.getCombinedNodeFlags(node) & 24576) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 211 && !node.initializer) { + if (node.kind === 213 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -20694,18 +21277,18 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212); - var container = varDeclList.parent.kind === 193 && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 214); + var container = varDeclList.parent.kind === 195 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 192 && ts.isFunctionLike(container.parent) || - container.kind === 219 || - container.kind === 218 || - container.kind === 248); + (container.kind === 194 && ts.isFunctionLike(container.parent) || + container.kind === 221 || + container.kind === 220 || + container.kind === 250); if (!namesShareScope) { - var name_15 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_15, name_15); + var name_14 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_14, name_14); } } } @@ -20747,7 +21330,7 @@ var ts; checkExpressionCached(node.initializer); } } - if (node.kind === 163) { + if (node.kind === 165) { if (node.propertyName && node.propertyName.kind === 136) { checkComputedPropertyName(node.propertyName); } @@ -20785,7 +21368,7 @@ var ts; } if (node.kind !== 141 && node.kind !== 140) { checkExportsOnMergedDeclarations(node); - if (node.kind === 211 || node.kind === 163) { + if (node.kind === 213 || node.kind === 165) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -20806,7 +21389,7 @@ var ts; ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 165) { + if (node.modifiers && node.parent.kind === 167) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -20825,7 +21408,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 194) { + if (node.thenStatement.kind === 196) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -20842,12 +21425,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 212) { + if (node.initializer && node.initializer.kind === 214) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 212) { + if (node.initializer.kind === 214) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -20862,13 +21445,13 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 214) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); - if (varExpr.kind === 164 || varExpr.kind === 165) { + if (varExpr.kind === 166 || varExpr.kind === 167) { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { @@ -20883,7 +21466,7 @@ var ts; } function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 214) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -20893,7 +21476,7 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 164 || varExpr.kind === 165) { + if (varExpr.kind === 166 || varExpr.kind === 167) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258)) { @@ -21021,7 +21604,13 @@ var ts; } function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); - var arrayType = removeTypesFromUnionType(arrayOrStringType, 258, true, true); + var arrayType = arrayOrStringType; + if (arrayOrStringType.flags & 16384) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258); })); + } + else if (arrayOrStringType.flags & 258) { + arrayType = emptyUnionType; + } var hasStringConstituent = arrayOrStringType !== arrayType; var reportedError = false; if (hasStringConstituent) { @@ -21081,7 +21670,7 @@ var ts; error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { + else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || returnType.flags & 134217728) { if (ts.isAsyncFunctionLike(func)) { var promisedType = getPromisedType(returnType); var awaitedType = checkAwaitedType(exprType, node.expression, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -21112,7 +21701,7 @@ var ts; var expressionType = checkExpression(node.expression); var expressionTypeIsStringLike = someConstituentTypeHasKind(expressionType, 258); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 242 && !hasDuplicateDefaultClause) { + if (clause.kind === 244 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -21124,13 +21713,12 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 241) { + if (produceDiagnostics && clause.kind === 243) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); - if (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258)) { - return; - } - if (!isTypeAssignableTo(expressionType, caseType)) { + var expressionTypeIsAssignableToCaseType = (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258)) || + isTypeAssignableTo(expressionType, caseType); + if (!expressionTypeIsAssignableToCaseType) { checkTypeAssignableTo(caseType, expressionType, caseClause.expression, undefined); } } @@ -21144,7 +21732,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 207 && current.label.text === node.label.text) { + if (current.kind === 209 && current.label.text === node.label.text) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; @@ -21284,8 +21872,12 @@ var ts; } function checkClassExpression(node) { checkClassLikeDeclaration(node); + checkNodeDeferred(node); return getTypeOfSymbol(getSymbolOfNode(node)); } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + } function checkClassDeclaration(node) { if (!node.name && !(node.flags & 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -21383,7 +21975,7 @@ var ts; if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(derivedClassDecl.flags & 128))) { - if (derivedClassDecl.kind === 186) { + if (derivedClassDecl.kind === 188) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -21493,7 +22085,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 215); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 217); if (symbol.declarations.length > 1) { if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { error(node.name, ts.Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); @@ -21558,7 +22150,8 @@ var ts; error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); } if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue++; + getNodeLinks(member).enumMemberValue = autoValue; + autoValue++; } } nodeLinks.flags |= 8192; @@ -21590,7 +22183,7 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 179: + case 181: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; @@ -21601,7 +22194,7 @@ var ts; case 50: return ~value_1; } return undefined; - case 181: + case 183: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -21626,11 +22219,11 @@ var ts; return undefined; case 8: return +e.text; - case 172: + case 174: return evalConstant(e.expression); case 69: - case 167: - case 166: + case 169: + case 168: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; @@ -21641,7 +22234,7 @@ var ts; } else { var expression; - if (e.kind === 167) { + if (e.kind === 169) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9) { return undefined; @@ -21658,7 +22251,7 @@ var ts; if (current.kind === 69) { break; } - else if (current.kind === 166) { + else if (current.kind === 168) { current = current.expression; } else { @@ -21717,7 +22310,7 @@ var ts; } var seenEnumMissingInitialInitializer = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 217) { + if (declaration.kind !== 219) { return false; } var enumDeclaration = declaration; @@ -21740,8 +22333,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 214 || - (declaration.kind === 213 && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 216 || + (declaration.kind === 215 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -21792,7 +22385,7 @@ var ts; error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); } } - var mergedClass = ts.getDeclarationOfKind(symbol, 214); + var mergedClass = ts.getDeclarationOfKind(symbol, 216); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768; @@ -21814,7 +22407,7 @@ var ts; if (node.kind === 135) { node = node.left; } - else if (node.kind === 166) { + else if (node.kind === 168) { node = node.expression; } else { @@ -21830,9 +22423,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 219 && node.parent.parent.name.kind === 9; - if (node.parent.kind !== 248 && !inAmbientExternalModule) { - error(moduleName, node.kind === 228 ? + var inAmbientExternalModule = node.parent.kind === 221 && node.parent.parent.name.kind === 9; + if (node.parent.kind !== 250 && !inAmbientExternalModule) { + error(moduleName, node.kind === 230 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -21851,7 +22444,7 @@ var ts; (symbol.flags & 793056 ? 793056 : 0) | (symbol.flags & 1536 ? 1536 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 230 ? + var message = node.kind === 232 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -21877,7 +22470,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224) { + if (importClause.namedBindings.kind === 226) { checkImportBinding(importClause.namedBindings); } else { @@ -21928,8 +22521,8 @@ var ts; if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause) { ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 219 && node.parent.parent.name.kind === 9; - if (node.parent.kind !== 248 && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 221 && node.parent.parent.name.kind === 9; + if (node.parent.kind !== 250 && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -21942,7 +22535,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 248 && node.parent.kind !== 219 && node.parent.kind !== 218) { + if (node.parent.kind !== 250 && node.parent.kind !== 221 && node.parent.kind !== 220) { return grammarErrorOnFirstToken(node, errorMessage); } } @@ -21956,8 +22549,8 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { return; } - var container = node.parent.kind === 248 ? node.parent : node.parent.parent; - if (container.kind === 218 && container.name.kind === 69) { + var container = node.parent.kind === 250 ? node.parent : node.parent.parent; + if (container.kind === 220 && container.name.kind === 69) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } @@ -21980,15 +22573,6 @@ var ts; } } } - function getModuleStatements(node) { - if (node.kind === 248) { - return node.statements; - } - if (node.kind === 218 && node.body.kind === 219) { - return node.body.statements; - } - return emptyArray; - } function hasExportedMembers(moduleSymbol) { for (var id in moduleSymbol.exports) { if (id !== "export=") { @@ -22006,13 +22590,41 @@ var ts; var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; 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) { + if (id === "__export") { + continue; + } + var _a = exports_2[id], declarations = _a.declarations, flags = _a.flags; + if (!(flags & (1536 | 64 | 384)) && (flags & 524288 ? declarations.length - 1 : declarations.length) > 1) { + var exportedDeclarations = ts.filter(declarations, isNotOverload); + if (exportedDeclarations.length > 1) { + for (var _i = 0, exportedDeclarations_1 = exportedDeclarations; _i < exportedDeclarations_1.length; _i++) { + var declaration = exportedDeclarations_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); + } + } + } + } links.exportsChecked = true; } + function isNotOverload(declaration) { + return declaration.kind !== 215 || !!declaration.body; + } } function checkTypePredicate(node) { - if (!isInLegalTypePredicatePosition(node)) { + var parameterName = node.parameterName; + if (parameterName.kind === 69 && !isInLegalParameterTypePredicatePosition(node)) { error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); } + else if (parameterName.kind === 161) { + if (!isInLegalThisTypePredicatePosition(node)) { + error(node, ts.Diagnostics.A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_return_type_positions_for_functions_and_methods); + } + else { + getTypeFromThisTypeNode(parameterName); + } + } } function checkSourceElement(node) { if (!node) { @@ -22021,10 +22633,10 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { - case 218: - case 214: + case 220: + case 216: + case 217: case 215: - case 213: cancellationToken.throwIfCancellationRequested(); } } @@ -22068,170 +22680,97 @@ var ts; return checkUnionOrIntersectionType(node); case 160: return checkSourceElement(node.type); - case 213: - return checkFunctionDeclaration(node); - case 192: - case 219: - return checkBlock(node); - case 193: - return checkVariableStatement(node); - case 195: - return checkExpressionStatement(node); - case 196: - return checkIfStatement(node); - case 197: - return checkDoStatement(node); - case 198: - return checkWhileStatement(node); - case 199: - return checkForStatement(node); - case 200: - return checkForInStatement(node); - case 201: - return checkForOfStatement(node); - case 202: - case 203: - return checkBreakOrContinueStatement(node); - case 204: - return checkReturnStatement(node); - case 205: - return checkWithStatement(node); - case 206: - return checkSwitchStatement(node); - case 207: - return checkLabeledStatement(node); - case 208: - return checkThrowStatement(node); - case 209: - return checkTryStatement(node); - case 211: - return checkVariableDeclaration(node); - case 163: - return checkBindingElement(node); - case 214: - return checkClassDeclaration(node); case 215: - return checkInterfaceDeclaration(node); - case 216: - return checkTypeAliasDeclaration(node); - case 217: - return checkEnumDeclaration(node); - case 218: - return checkModuleDeclaration(node); - case 222: - return checkImportDeclaration(node); - case 221: - return checkImportEqualsDeclaration(node); - case 228: - return checkExportDeclaration(node); - case 227: - return checkExportAssignment(node); + return checkFunctionDeclaration(node); case 194: - checkGrammarStatementInAmbientContext(node); - return; + case 221: + return checkBlock(node); + case 195: + return checkVariableStatement(node); + case 197: + return checkExpressionStatement(node); + case 198: + return checkIfStatement(node); + case 199: + return checkDoStatement(node); + case 200: + return checkWhileStatement(node); + case 201: + return checkForStatement(node); + case 202: + return checkForInStatement(node); + case 203: + return checkForOfStatement(node); + case 204: + case 205: + return checkBreakOrContinueStatement(node); + case 206: + return checkReturnStatement(node); + case 207: + return checkWithStatement(node); + case 208: + return checkSwitchStatement(node); + case 209: + return checkLabeledStatement(node); case 210: + return checkThrowStatement(node); + case 211: + return checkTryStatement(node); + case 213: + return checkVariableDeclaration(node); + case 165: + return checkBindingElement(node); + case 216: + return checkClassDeclaration(node); + case 217: + return checkInterfaceDeclaration(node); + case 218: + return checkTypeAliasDeclaration(node); + case 219: + return checkEnumDeclaration(node); + case 220: + return checkModuleDeclaration(node); + case 224: + return checkImportDeclaration(node); + case 223: + return checkImportEqualsDeclaration(node); + case 230: + return checkExportDeclaration(node); + case 229: + return checkExportAssignment(node); + case 196: checkGrammarStatementInAmbientContext(node); return; - case 231: + case 212: + checkGrammarStatementInAmbientContext(node); + return; + case 233: return checkMissingDeclaration(node); } } - function checkFunctionAndClassExpressionBodies(node) { - switch (node.kind) { - case 173: - case 174: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - checkFunctionExpressionOrObjectLiteralMethodBody(node); - break; - case 186: - ts.forEach(node.members, checkSourceElement); - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; - case 143: - case 142: - ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - if (ts.isObjectLiteralMethod(node)) { - checkFunctionExpressionOrObjectLiteralMethodBody(node); - } - break; - case 144: - case 145: - case 146: - case 213: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - break; - case 205: - checkFunctionAndClassExpressionBodies(node.expression); - break; - case 139: - case 138: - case 141: - case 140: - case 161: - case 162: - case 163: - case 164: - case 165: - case 245: - case 166: - case 167: - case 168: - case 169: - case 170: - case 183: - case 190: - case 171: - case 189: - case 172: - case 176: - case 177: - case 178: - case 175: - case 179: - case 180: - case 181: - case 182: - case 185: - case 184: - case 192: - case 219: - case 193: - case 195: - case 196: - case 197: - case 198: - case 199: - case 200: - case 201: - case 202: - case 203: - case 204: - case 206: - case 220: - case 241: - case 242: - case 207: - case 208: - case 209: - case 244: - case 211: - case 212: - case 214: - case 243: - case 188: - case 217: - case 247: - case 227: - case 248: - case 240: - case 233: - case 234: - case 238: - case 239: - case 235: - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 175: + case 176: + case 143: + case 142: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 145: + case 146: + checkAccessorDeferred(node); + break; + case 188: + checkClassExpressionDeferred(node); + break; + } } } function checkSourceFile(node) { @@ -22251,9 +22790,12 @@ var ts; emitExtends = false; emitDecorate = false; emitParam = false; + emitAwaiter = false; potentialThisCollisions.length = 0; + deferredNodes = []; ts.forEach(node.statements, checkSourceElement); - checkFunctionAndClassExpressionBodies(node); + checkDeferredNodes(); + deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -22309,7 +22851,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 205 && node.parent.statement === node) { + if (node.parent.kind === 207 && node.parent.statement === node) { return true; } node = node.parent; @@ -22331,28 +22873,28 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 248: + case 250: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 218: + case 220: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); break; - case 217: + case 219: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 186: + case 188: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 214: - case 215: + case 216: + case 217: if (!(memberFlags & 64)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; - case 173: + case 175: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -22392,10 +22934,10 @@ var ts; function isTypeDeclaration(node) { switch (node.kind) { case 137: - case 214: - case 215: case 216: case 217: + case 218: + case 219: return true; } } @@ -22408,19 +22950,19 @@ var ts; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 166) { + while (node.parent && node.parent.kind === 168) { node = node.parent; } - return node.parent && node.parent.kind === 188; + return node.parent && node.parent.kind === 190; } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { while (nodeOnRightSide.parent.kind === 135) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 221) { + if (nodeOnRightSide.parent.kind === 223) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 227) { + if (nodeOnRightSide.parent.kind === 229) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -22432,10 +22974,10 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 227) { + if (entityName.parent.kind === 229) { return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); } - if (entityName.kind !== 166) { + if (entityName.kind !== 168) { if (isInRightSideOfImportOrExportAssignment(entityName)) { return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); } @@ -22445,7 +22987,7 @@ var ts; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; - if (entityName.parent.kind === 188) { + if (entityName.parent.kind === 190) { meaning = 793056; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; @@ -22457,9 +22999,9 @@ var ts; meaning |= 8388608; return resolveEntityName(entityName, meaning); } - else if ((entityName.parent.kind === 235) || - (entityName.parent.kind === 234) || - (entityName.parent.kind === 237)) { + else if ((entityName.parent.kind === 237) || + (entityName.parent.kind === 236) || + (entityName.parent.kind === 239)) { return getJsxElementTagSymbol(entityName.parent); } else if (ts.isExpression(entityName)) { @@ -22470,7 +23012,7 @@ var ts; var meaning = 107455 | 8388608; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 166) { + else if (entityName.kind === 168) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); @@ -22490,7 +23032,7 @@ var ts; meaning |= 8388608; return resolveEntityName(entityName, meaning); } - else if (entityName.parent.kind === 238) { + else if (entityName.parent.kind === 240) { return getJsxAttributePropertySymbol(entityName.parent); } if (entityName.parent.kind === 150) { @@ -22507,12 +23049,12 @@ var ts; } if (node.kind === 69) { if (isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 227 + return node.parent.kind === 229 ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } - else if (node.parent.kind === 163 && - node.parent.parent.kind === 161 && + else if (node.parent.kind === 165 && + node.parent.parent.kind === 163 && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -22523,13 +23065,15 @@ var ts; } switch (node.kind) { case 69: - case 166: + case 168: case 135: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 97: case 95: var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; + case 161: + return getTypeFromTypeNode(node).symbol; case 121: var constructorDeclaration = node.parent; if (constructorDeclaration && constructorDeclaration.kind === 144) { @@ -22539,12 +23083,12 @@ var ts; case 9: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 222 || node.parent.kind === 228) && + ((node.parent.kind === 224 || node.parent.kind === 230) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } case 8: - if (node.parent.kind === 167 && node.parent.argumentExpression === node) { + if (node.parent.kind === 169 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -22558,7 +23102,7 @@ var ts; return undefined; } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 246) { + if (location && location.kind === 248) { return resolveEntityName(location.name, 107455); } return undefined; @@ -22629,9 +23173,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols = []; - var name_16 = symbol.name; + var name_15 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_16); + var symbol = getPropertyOfType(t, name_15); if (symbol) { symbols.push(symbol); } @@ -22649,6 +23193,25 @@ var ts; function isArgumentsLocalBinding(node) { return getReferencedValueSymbol(node) === argumentsSymbol; } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol) { + return true; + } + var hasExportAssignment = getExportAssignmentSymbol(moduleSymbol) !== undefined; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455) + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455); + } + } function getReferencedExportContainer(node) { var symbol = getReferencedValueSymbol(node); if (symbol) { @@ -22661,11 +23224,11 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 248) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 250) { return parentSymbol.valueDeclaration; } for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 218 || n.kind === 217) && getSymbolOfNode(n) === parentSymbol) { + if ((n.kind === 220 || n.kind === 219) && getSymbolOfNode(n) === parentSymbol) { return n; } } @@ -22678,11 +23241,11 @@ var ts; } function isStatementWithLocals(node) { switch (node.kind) { - case 192: - case 220: - case 199: - case 200: + case 194: + case 222: case 201: + case 202: + case 203: return true; } return false; @@ -22708,22 +23271,22 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 221: case 223: - case 224: + case 225: case 226: - case 230: - return isAliasResolvedToValue(getSymbolOfNode(node)); case 228: + case 232: + return isAliasResolvedToValue(getSymbolOfNode(node)); + case 230: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 227: + case 229: return node.expression && node.expression.kind === 69 ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 248 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 250 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -22771,7 +23334,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 247) { + if (node.kind === 249) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -22857,17 +23420,6 @@ var ts; var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } - function instantiateSingleCallFunctionType(functionType, typeArguments) { - if (functionType === unknownType) { - return unknownType; - } - var signature = getSingleCallSignature(functionType); - if (!signature) { - return unknownType; - } - var instantiatedSignature = getSignatureInstantiation(signature, typeArguments); - return getOrCreateTypeFromSignature(instantiatedSignature); - } function createResolver() { return { getReferencedExportContainer: getReferencedExportContainer, @@ -22891,6 +23443,7 @@ var ts; getReferencedValueDeclaration: getReferencedValueDeclaration, getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, isArgumentsLocalBinding: isArgumentsLocalBinding, getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration }; @@ -22901,7 +23454,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 248); + return ts.getDeclarationOfKind(moduleSymbol, 250); } function initializeTypeChecker() { ts.forEach(host.getSourceFiles(), function (file) { @@ -22912,10 +23465,10 @@ var ts; mergeSymbolTable(globals, file.locals); } }); + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); getSymbolLinks(unknownSymbol).type = unknownType; - globals[undefinedSymbol.name] = undefinedSymbol; globalArrayType = getGlobalType("Array", 1); globalObjectType = getGlobalType("Object"); globalFunctionType = getGlobalType("Function"); @@ -22976,7 +23529,12 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + if (node.kind === 143 && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } } else if (node.kind === 145 || node.kind === 146) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); @@ -22996,30 +23554,30 @@ var ts; case 143: case 142: case 149: - case 218: - case 222: - case 221: - case 228: - case 227: + case 220: + case 224: + case 223: + case 230: + case 229: case 138: break; - case 213: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && - node.parent.kind !== 219 && node.parent.kind !== 248) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 214: case 215: - case 193: - case 216: - if (node.modifiers && node.parent.kind !== 219 && node.parent.kind !== 248) { + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && + node.parent.kind !== 221 && node.parent.kind !== 250) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; + case 216: case 217: + case 195: + case 218: + if (node.modifiers && node.parent.kind !== 221 && node.parent.kind !== 250) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 219: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74) && - node.parent.kind !== 219 && node.parent.kind !== 248) { + node.parent.kind !== 221 && node.parent.kind !== 250) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; @@ -23034,6 +23592,11 @@ var ts; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; switch (modifier.kind) { + case 74: + if (node.kind !== 219 && node.parent.kind === 216) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74)); + } + break; case 112: case 111: case 110: @@ -23058,7 +23621,7 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 219 || node.parent.kind === 248) { + else if (node.parent.kind === 221 || node.parent.kind === 250) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } else if (flags & 128) { @@ -23078,7 +23641,7 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 219 || node.parent.kind === 248) { + else if (node.parent.kind === 221 || node.parent.kind === 250) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); } else if (node.kind === 138) { @@ -23103,7 +23666,7 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 216) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } else if (node.kind === 138) { @@ -23118,13 +23681,13 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 216) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } else if (node.kind === 138) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 221) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 4; @@ -23134,11 +23697,11 @@ var ts; if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 214) { + if (node.kind !== 216) { if (node.kind !== 143) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); } - if (!(node.parent.kind === 214 && node.parent.flags & 128)) { + if (!(node.parent.kind === 216 && node.parent.flags & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 64) { @@ -23183,7 +23746,7 @@ var ts; } return; } - else if ((node.kind === 222 || node.kind === 221) && flags & 4) { + else if ((node.kind === 224 || node.kind === 223) && flags & 4) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 138 && (flags & 56) && ts.isBindingPattern(node.name)) { @@ -23199,9 +23762,9 @@ var ts; } switch (node.kind) { case 143: - case 213: - case 173: - case 174: + case 215: + case 175: + case 176: if (!node.asteriskToken) { return false; } @@ -23266,7 +23829,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 174) { + if (node.kind === 176) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -23333,7 +23896,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { var arg = args_1[_i]; - if (arg.kind === 187) { + if (arg.kind === 189) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -23408,14 +23971,14 @@ var ts; return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 181 && computedPropertyName.expression.operatorToken.kind === 24) { + if (computedPropertyName.expression.kind === 183 && computedPropertyName.expression.operatorToken.kind === 24) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 213 || - node.kind === 173 || + ts.Debug.assert(node.kind === 215 || + node.kind === 175 || node.kind === 143); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); @@ -23439,22 +24002,26 @@ var ts; var GetAccessor = 2; var SetAccesor = 4; var GetOrSetAccessor = GetAccessor | SetAccesor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - var name_17 = prop.name; - if (prop.kind === 187 || - name_17.kind === 136) { - checkGrammarComputedPropertyName(name_17); - continue; + var _loop_1 = function(prop) { + var name_16 = prop.name; + if (prop.kind === 189 || + name_16.kind === 136) { + checkGrammarComputedPropertyName(name_16); + return "continue"; } - if (prop.kind === 246 && !inDestructuring && prop.objectAssignmentInitializer) { - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + if (prop.kind === 248 && !inDestructuring && prop.objectAssignmentInitializer) { + return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; } + ts.forEach(prop.modifiers, function (mod) { + if (mod.kind !== 118 || prop.kind !== 143) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + }); var currentKind = void 0; - if (prop.kind === 245 || prop.kind === 246) { + if (prop.kind === 247 || prop.kind === 248) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_17.kind === 8) { - checkGrammarNumericLiteral(name_17); + if (name_16.kind === 8) { + checkGrammarNumericLiteral(name_16); } currentKind = Property; } @@ -23470,45 +24037,51 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_17.text)) { - seen[name_17.text] = currentKind; + if (!ts.hasProperty(seen, name_16.text)) { + seen[name_16.text] = currentKind; } else { - var existingKind = seen[name_17.text]; + var existingKind = seen[name_16.text]; if (currentKind === Property && existingKind === Property) { - continue; + return "continue"; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_17.text] = currentKind | existingKind; + seen[name_16.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_17, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return { value: grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return grammarErrorOnNode(name_17, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return { value: grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } + }; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var state_1 = _loop_1(prop); + if (typeof state_1 === "object") return state_1.value + if (state_1 === "continue") continue; } } function checkGrammarJsxElement(node) { var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 239) { + if (attr.kind === 241) { continue; } var jsxAttr = attr; - var name_18 = jsxAttr.name; - if (!ts.hasProperty(seen, name_18.text)) { - seen[name_18.text] = true; + var name_17 = jsxAttr.name; + if (!ts.hasProperty(seen, name_17.text)) { + seen[name_17.text] = true; } else { - return grammarErrorOnNode(name_18, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_17, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 240 && !initializer.expression) { + if (initializer && initializer.kind === 242 && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -23517,24 +24090,28 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 212) { + if (forInOrOfStatement.initializer.kind === 214) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { - if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 200 + var declarations = variableList.declarations; + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 202 ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } - var firstDeclaration = variableList.declarations[0]; + var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 200 + var diagnostic = forInOrOfStatement.kind === 202 ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 200 + var diagnostic = forInOrOfStatement.kind === 202 ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -23595,7 +24172,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 165) { + if (node.parent.kind === 167) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -23614,7 +24191,7 @@ var ts; return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); } } - else if (node.parent.kind === 215) { + else if (node.parent.kind === 217) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); } else if (node.parent.kind === 155) { @@ -23628,9 +24205,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 207: + case 209: if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 202 + var isMisplacedContinueLabel = node.kind === 204 && !ts.isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -23638,8 +24215,8 @@ var ts; return false; } break; - case 206: - if (node.kind === 203 && !node.label) { + case 208: + if (node.kind === 205 && !node.label) { return false; } break; @@ -23652,13 +24229,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 203 + var message = node.kind === 205 ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 203 + var message = node.kind === 205 ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -23670,7 +24247,7 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } - if (node.name.kind === 162 || node.name.kind === 161) { + if (node.name.kind === 164 || node.name.kind === 163) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -23679,7 +24256,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 200 && node.parent.parent.kind !== 201) { + if (node.parent.parent.kind !== 202 && node.parent.parent.kind !== 203) { if (ts.isInAmbientContext(node)) { if (node.initializer) { var equalsTokenLength = "=".length; @@ -23695,12 +24272,12 @@ var ts; } } } - var checkLetConstNames = languageVersion >= 2 && (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 69) { - if (name.text === "let") { + if (name.originalKeywordKind === 108) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -23708,7 +24285,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 187) { + if (element.kind !== 189) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -23725,15 +24302,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 196: - case 197: case 198: - case 205: case 199: case 200: - case 201: - return false; case 207: + case 201: + case 202: + case 203: + return false; + case 209: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -23748,18 +24325,6 @@ var ts; } } } - function isIntegerLiteral(expression) { - if (expression.kind === 179) { - var unaryExpression = expression; - if (unaryExpression.operator === 35 || unaryExpression.operator === 36) { - expression = unaryExpression.operand; - } - } - if (expression.kind === 8) { - return /^[0-9]+([eE]\+?[0-9]+)?$/.test(expression.text); - } - return false; - } function hasParseDiagnostics(sourceFile) { return sourceFile.parseDiagnostics.length > 0; } @@ -23784,10 +24349,6 @@ var ts; return true; } } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 && - (node.text === "eval" || node.text === "arguments"); - } function checkGrammarConstructorTypeParameters(node) { if (node.typeParameters) { return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); @@ -23805,27 +24366,33 @@ var ts; return true; } } - else if (node.parent.kind === 215) { + else if (node.parent.kind === 217) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } } else if (node.parent.kind === 155) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } } if (ts.isInAmbientContext(node) && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 215 || - node.kind === 216 || - node.kind === 222 || - node.kind === 221 || - node.kind === 228 || - node.kind === 227 || + if (node.kind === 217 || + node.kind === 218 || + node.kind === 224 || + node.kind === 223 || + node.kind === 230 || + node.kind === 229 || (node.flags & 4) || (node.flags & (2 | 512))) { return false; @@ -23835,7 +24402,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 193) { + if (ts.isDeclaration(decl) || decl.kind === 195) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -23854,7 +24421,7 @@ var ts; if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } - if (node.parent.kind === 192 || node.parent.kind === 219 || node.parent.kind === 248) { + if (node.parent.kind === 194 || node.parent.kind === 221 || node.parent.kind === 250) { var links_1 = getNodeLinks(node.parent); if (!links_1.hasReportedStatementInAmbientContext) { return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -23877,19 +24444,248 @@ var ts; return true; } } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); var ts; +(function (ts) { + var nullSourceMapWriter; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitStart: function (range) { }, + emitEnd: function (range) { }, + emitPos: function (pos) { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; }, + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + var currentSourceFile; + var sourceMapDir; + var sourceMapSourceIndex; + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan; + var lastEncodedNameIndex; + var sourceMapData; + return { + getSourceMapData: function () { return sourceMapData; }, + setSourceFile: setSourceFile, + emitPos: emitPos, + emitStart: emitStart, + emitEnd: emitEnd, + getText: getText, + getSourceMappingURL: getSourceMappingURL, + initialize: initialize, + reset: reset + }; + function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (sourceMapData) { + reset(); + } + currentSourceFile = undefined; + sourceMapSourceIndex = -1; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + lastEncodedNameIndex = 0; + sourceMapData = { + sourceMapFilePath: sourceMapFilePath, + jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, + sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, + sourceMapDecodedMappings: [] + }; + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (!isBundledEmit) { + ts.Debug.assert(sourceFiles.length === 1); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); + } + } + function reset() { + currentSourceFile = undefined; + sourceMapDir = undefined; + sourceMapSourceIndex = undefined; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = undefined; + lastEncodedNameIndex = undefined; + sourceMapData = undefined; + } + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + } + function emitPos(pos) { + if (pos === -1) { + return; + } + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + sourceLinePos.line++; + sourceLinePos.character++; + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + if (!lastRecordedSourceMapSpan || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || + (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && + (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || + (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + sourceIndex: sourceMapSourceIndex + }; + } + else { + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + } + function emitStart(range) { + var rangeHasDecorators = !!range.decorators; + emitPos(range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1); + } + function emitEnd(range) { + emitPos(range.end); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + if (sourceMapSourceIndex === -1) { + sourceMapSourceIndex = sourceMapData.sourceMapSources.length; + sourceMapData.sourceMapSources.push(source); + sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + if (compilerOptions.inlineSources) { + sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + } + } + } + function getText() { + encodeLastRecordedSourceMapSpan(); + return ts.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent + }); + } + function getSourceMappingURL() { + if (compilerOptions.inlineSourceMap) { + var base64SourceMapText = ts.convertToBase64(getText()); + return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; + } + else { + return sourceMapData.jsSourceMappingURL; + } + } + } + ts.createSourceMapWriter = createSourceMapWriter; + var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function base64FormatEncode(inValue) { + if (inValue < 64) { + return base64Chars.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + function base64VLQFormatEncode(inValue) { + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } +})(ts || (ts = {})); +var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var diagnostics = []; - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); - emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); - return diagnostics; + var declarationDiagnostics = ts.createDiagnosticCollection(); + ts.forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); + return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName); + function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { + var declarationFilePath = _a.declarationFilePath; + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -23907,93 +24703,67 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare = !root; + var noDeclare; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencePathsOutput = ""; - if (root) { + var emittedReferencedFiles = []; + var addedGlobalFileReference = false; + var allSourcesModuleElementDeclarationEmitInfo = []; + ts.forEach(sourceFiles, function (sourceFile) { + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } if (!compilerOptions.noResolve) { - var addedGlobalFileReference = false; - ts.forEach(root.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); - if (referencedFile && ((referencedFile.flags & 4096) || - ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || - !addedGlobalFileReference)) { - writeReferencePath(referencedFile); - if (!ts.isExternalModuleOrDeclarationFile(referencedFile)) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } + emittedReferencedFiles.push(referencedFile); } }); } - emitSourceFile(root); + if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { + noDeclare = false; + emitSourceFile(sourceFile); + } + else if (ts.isExternalModule(sourceFile)) { + noDeclare = true; + write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); + writeLine(); + increaseIndent(); + emitSourceFile(sourceFile); + decreaseIndent(); + write("}"); + writeLine(); + } if (moduleElementDeclarationEmitInfo.length) { var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222); + if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { + ts.Debug.assert(aliasEmitInfo.node.kind === 224); createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0); + ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + increaseIndent(); + } writeImportDeclaration(aliasEmitInfo.node); aliasEmitInfo.asynchronousOutput = writer.getText(); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + decreaseIndent(); + } } }); setWriter(oldWriter); + allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); + moduleElementDeclarationEmitInfo = []; } - } - else { - var emittedReferencedFiles = []; - var prevModuleElementDeclarationEmitInfo = []; - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!ts.isDeclarationFile(sourceFile)) { - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - if (referencedFile && (ts.isDeclarationFile(referencedFile) && - !ts.contains(emittedReferencedFiles, referencedFile))) { - writeReferencePath(referencedFile); - emittedReferencedFiles.push(referencedFile); - } - }); - } - } - if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) { - noDeclare = false; - emitSourceFile(sourceFile); - } - else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; - write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - write("}"); - writeLine(); - if (moduleElementDeclarationEmitInfo.length) { - var oldWriter = writer; - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222); - createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 1); - increaseIndent(); - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - decreaseIndent(); - } - }); - setWriter(oldWriter); - } - prevModuleElementDeclarationEmitInfo = prevModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - }); - moduleElementDeclarationEmitInfo = moduleElementDeclarationEmitInfo.concat(prevModuleElementDeclarationEmitInfo); - } + }); return { reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: moduleElementDeclarationEmitInfo, + moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), referencePathsOutput: referencePathsOutput }; @@ -24036,10 +24806,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 211) { + if (declaration.kind === 213) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 225 || declaration.kind === 226 || declaration.kind === 223) { + else if (declaration.kind === 227 || declaration.kind === 228 || declaration.kind === 225) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -24050,7 +24820,7 @@ var ts; moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 222) { + if (moduleElementEmitInfo.node.kind === 224) { moduleElementEmitInfo.isVisible = true; } else { @@ -24058,12 +24828,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 218) { + if (nodeToCheck.kind === 220) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 218) { + if (nodeToCheck.kind === 220) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -24084,10 +24854,10 @@ var ts; var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); if (errorInfo) { if (errorInfo.typeName) { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); } else { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); } } } @@ -24097,7 +24867,8 @@ var ts; } function reportInaccessibleThisError() { if (errorNameNode) { - diagnostics.push(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { @@ -24165,10 +24936,10 @@ var ts; case 120: case 131: case 103: - case 97: - case 9: + case 161: + case 162: return writeTextOfNode(currentText, type); - case 188: + case 190: return emitExpressionWithTypeArguments(type); case 151: return emitTypeReference(type); @@ -24209,13 +24980,13 @@ var ts; } } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 221 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 223 ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 166); + ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 168); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -24288,9 +25059,10 @@ var ts; } var count = 0; while (true) { - var name_19 = baseName + "_" + (++count); - if (!ts.hasProperty(currentIdentifiers, name_19)) { - return name_19; + count++; + var name_18 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_18)) { + return name_18; } } } @@ -24331,10 +25103,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 221 || - (node.parent.kind === 248 && isCurrentFileExternalModule)) { + else if (node.kind === 223 || + (node.parent.kind === 250 && isCurrentFileExternalModule)) { var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 250) { asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -24343,7 +25115,7 @@ var ts; }); } else { - if (node.kind === 222) { + if (node.kind === 224) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -24361,37 +25133,37 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 213: - return writeFunctionDeclaration(node); - case 193: - return writeVariableStatement(node); case 215: - return writeInterfaceDeclaration(node); - case 214: - return writeClassDeclaration(node); - case 216: - return writeTypeAliasDeclaration(node); + return writeFunctionDeclaration(node); + case 195: + return writeVariableStatement(node); case 217: - return writeEnumDeclaration(node); + return writeInterfaceDeclaration(node); + case 216: + return writeClassDeclaration(node); case 218: + return writeTypeAliasDeclaration(node); + case 219: + return writeEnumDeclaration(node); + case 220: return writeModuleDeclaration(node); - case 221: + case 223: return writeImportEqualsDeclaration(node); - case 222: + case 224: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); } } function emitModuleElementDeclarationFlags(node) { - if (node.parent.kind === 248) { + if (node.parent.kind === 250) { if (node.flags & 2) { write("export "); } if (node.flags & 512) { write("default "); } - else if (node.kind !== 215 && !noDeclare) { + else if (node.kind !== 217 && !noDeclare) { write("declare "); } } @@ -24424,7 +25196,7 @@ var ts; } else { write("require("); - writeTextOfNode(currentText, ts.getExternalModuleImportEqualsDeclarationExpression(node)); + emitExternalModuleSpecifier(node); write(");"); } writer.writeLine(); @@ -24438,7 +25210,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 224) { + if (namedBindings.kind === 226) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -24464,7 +25236,7 @@ var ts; if (currentWriterPos !== writer.getTextPos()) { write(", "); } - if (node.importClause.namedBindings.kind === 224) { + if (node.importClause.namedBindings.kind === 226) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -24476,13 +25248,22 @@ var ts; } write(" from "); } - emitExternalModuleSpecifier(node.moduleSpecifier); + emitExternalModuleSpecifier(node); write(";"); writer.writeLine(); } - function emitExternalModuleSpecifier(moduleSpecifier) { - if (moduleSpecifier.kind === 9 && (!root) && (compilerOptions.out || compilerOptions.outFile)) { - var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, moduleSpecifier.parent); + function emitExternalModuleSpecifier(parent) { + var moduleSpecifier; + if (parent.kind === 223) { + var node = parent; + moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); + } + else { + var node = parent; + moduleSpecifier = node.moduleSpecifier; + } + if (moduleSpecifier.kind === 9 && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { + var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); if (moduleName) { write("\""); write(moduleName); @@ -24517,7 +25298,7 @@ var ts; } if (node.moduleSpecifier) { write(" from "); - emitExternalModuleSpecifier(node.moduleSpecifier); + emitExternalModuleSpecifier(node); } write(";"); writer.writeLine(); @@ -24532,7 +25313,7 @@ var ts; write("module "); } writeTextOfNode(currentText, node.name); - while (node.body.kind !== 219) { + while (node.body.kind !== 221) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -24625,10 +25406,10 @@ var ts; function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; switch (node.parent.kind) { - case 214: + case 216: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 215: + case 217: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; case 148: @@ -24642,14 +25423,14 @@ var ts; if (node.parent.flags & 64) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 214) { + else if (node.parent.parent.kind === 216) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 213: + case 215: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -24682,7 +25463,7 @@ var ts; } function getHeritageClauseVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; - if (node.parent.parent.kind === 214) { + if (node.parent.parent.kind === 216) { diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; @@ -24762,7 +25543,7 @@ var ts; writeLine(); } function emitVariableDeclaration(node) { - if (node.kind !== 211 || resolver.isDeclarationVisible(node)) { + if (node.kind !== 213 || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } @@ -24780,7 +25561,7 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 211) { + if (node.kind === 213) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24795,7 +25576,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 216) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24821,7 +25602,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187) { + if (element.kind !== 189) { elements.push(element); } } @@ -24955,13 +25736,13 @@ var ts; } if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 213) { + if (node.kind === 215) { emitModuleElementDeclarationFlags(node); } else if (node.kind === 143) { emitClassMemberDeclarationFlags(node); } - if (node.kind === 213) { + if (node.kind === 215) { write("function "); writeTextOfNode(currentText, node.name); } @@ -24982,6 +25763,8 @@ var ts; emitSignatureDeclaration(node); } function emitSignatureDeclaration(node) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; if (node.kind === 148 || node.kind === 153) { write("new "); } @@ -24992,8 +25775,6 @@ var ts; else { write("("); } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitCommaList(node.parameters, emitParameterDeclaration); if (node.kind === 149) { write("]"); @@ -25043,7 +25824,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 216) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -25056,7 +25837,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 213: + case 215: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -25129,7 +25910,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 214) { + else if (node.parent.parent.kind === 216) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -25141,7 +25922,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 213: + case 215: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -25152,12 +25933,12 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 161) { + if (bindingPattern.kind === 163) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 162) { + else if (bindingPattern.kind === 164) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -25168,18 +25949,10 @@ var ts; } } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.kind === 187) { + if (bindingElement.kind === 189) { write(" "); } - else if (bindingElement.kind === 163) { + else if (bindingElement.kind === 165) { if (bindingElement.propertyName) { writeTextOfNode(currentText, bindingElement.propertyName); write(": "); @@ -25201,19 +25974,19 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 213: - case 218: - case 221: case 215: - case 214: - case 216: + case 220: + case 223: case 217: + case 216: + case 218: + case 219: return emitModuleElement(node, isModuleElementVisible(node)); - case 193: + case 195: return emitModuleElement(node, isVariableStatementVisible(node)); - case 222: + case 224: return emitModuleElement(node, !node.importClause); - case 228: + case 230: return emitExportDeclaration(node); case 144: case 143: @@ -25229,31 +26002,47 @@ var ts; case 141: case 140: return emitPropertyDeclaration(node); - case 247: + case 249: return emitEnumMemberDeclaration(node); - case 227: + case 229: return emitExportAssignment(node); - case 248: + case 250: return emitSourceFile(node); } } - function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 4096 - ? referencedFile.fileName - : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) - ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") - : ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); - referencePathsOutput += "/// " + newLine; + function writeReferencePath(referencedFile, addBundledFileReference) { + var declFileName; + var addedBundledEmitReference = false; + if (ts.isDeclarationFile(referencedFile)) { + declFileName = referencedFile.fileName; + } + else { + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + } + if (declFileName) { + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); + referencePathsOutput += "/// " + newLine; + } + return addedBundledEmitReference; + function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + if (isBundledEmit && !addBundledFileReference) { + return; + } + ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); + declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; + addedBundledEmitReference = isBundledEmit; + } } } - function writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); - if (!emitDeclarationResult.reportedDeclarationError) { + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; + if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); + ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM); } + return emitSkipped; function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { var appliedSyncOutputPos = 0; var declarationOutput = ""; @@ -25272,10 +26061,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); - } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; function getResolvedExternalModuleName(host, file) { return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); } @@ -25550,41 +26335,17 @@ var ts; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\n return new Promise(function (resolve, reject) {\n generator = generator.call(thisArg, _arguments);\n function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\n function onfulfill(value) { try { step(\"next\", value); } catch (e) { reject(e); } }\n function onreject(value) { try { step(\"throw\", value); } catch (e) { reject(e); } }\n function step(verb, value) {\n var result = generator[verb](value);\n result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\n }\n step(\"next\", void 0);\n });\n};"; var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || 0; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 ? 5 : 0; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; - var diagnostics = []; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emitSkipped = false; var newLine = host.getNewLine(); - var jsxDesugaring = host.getCompilerOptions().jsx !== 1; - var shouldEmitJsx = function (s) { return (s.languageVariant === 1 && !jsxDesugaring); }; - var outFile = compilerOptions.outFile || compilerOptions.out; var emitJavaScript = createFileEmitter(); - if (targetSourceFile === undefined) { - if (outFile) { - emitFile(outFile); - } - else { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - } - } - else { - if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!ts.isDeclarationFile(targetSourceFile) && outFile) { - emitFile(outFile); - } - } - diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { - emitSkipped: false, - diagnostics: diagnostics, + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), sourceMaps: sourceMapDataList }; function isUniqueLocalName(name, container) { @@ -25631,6 +26392,8 @@ var ts; function createFileEmitter() { var writer = ts.createTextWriter(newLine); var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); + var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; var currentSourceFile; var currentText; var currentLineMap; @@ -25647,24 +26410,16 @@ var ts; var decorateEmitted; var paramEmitted; var awaiterEmitted; - var tempFlags; + var tempFlags = 0; var tempVariables; var tempParameters; var externalImports; var exportSpecifiers; var exportEquals; - var hasExportStars; - var writeEmittedFiles = writeJavaScriptFile; + var hasExportStarsToExportValues; var detachedCommentsInfo; - var writeComment = ts.writeCommentRange; - var emit = emitNodeWithCommentsAndWithoutSourcemap; - var emitStart = function (node) { }; - var emitEnd = function (node) { }; - var emitToken = emitTokenText; - var scopeEmitStart = function (scopeDeclaration, scopeName) { }; - var scopeEmitEnd = function () { }; var sourceMapData; - var root; + var isOwnFileEmit; var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var moduleEmitDelegates = (_a = {}, _a[5] = emitES6Module, @@ -25683,14 +26438,29 @@ var ts; _b ); return doEmit; - function doEmit(jsFilePath, rootFile) { + function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + generatedNameSet = {}; + nodeToGeneratedName = []; + isOwnFileEmit = !isBundledEmit; + if (isBundledEmit && modulekind) { + ts.forEach(sourceFiles, emitEmitHelpers); + } + ts.forEach(sourceFiles, emitSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# sourceMappingURL=" + sourceMappingURL); + } + writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM); + sourceMap.reset(); writer.reset(); currentSourceFile = undefined; currentText = undefined; currentLineMap = undefined; exportFunctionForFile = undefined; - generatedNameSet = {}; - nodeToGeneratedName = []; + generatedNameSet = undefined; + nodeToGeneratedName = undefined; computedPropertyNamesToGeneratedNames = undefined; convertedLoopState = undefined; extendsEmitted = false; @@ -25703,31 +26473,12 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = undefined; + hasExportStarsToExportValues = undefined; detachedCommentsInfo = undefined; sourceMapData = undefined; isEs6Module = false; renamedDependencies = undefined; isCurrentFileExternalModule = false; - root = rootFile; - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - initializeEmitterWithSourceMaps(jsFilePath, root); - } - if (root) { - emitSourceFile(root); - } - else { - if (modulekind) { - ts.forEach(host.getSourceFiles(), emitEmitHelpers); - } - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if ((!isExternalModuleOrDeclarationFile(sourceFile)) || (modulekind && ts.isExternalModule(sourceFile))) { - emitSourceFile(sourceFile); - } - }); - } - writeLine(); - writeEmittedFiles(writer.getText(), jsFilePath, compilerOptions.emitBOM); } function emitSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -25738,7 +26489,8 @@ var ts; renamedDependencies = sourceFile.renamedDependencies; currentFileIdentifiers = sourceFile.identifiers; isCurrentFileExternalModule = ts.isExternalModule(sourceFile); - emit(sourceFile); + setSourceFile(sourceFile); + emitNodeWithCommentsAndWithoutSourcemap(sourceFile); } function isUniqueName(name) { return !resolver.hasGlobalName(name) && @@ -25747,19 +26499,19 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_20 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_20)) { + var name_19 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_19)) { tempFlags |= flags; - return name_20; + return name_19; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_21 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_21)) { - return name_21; + var name_20 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_20)) { + return name_20; } } } @@ -25797,17 +26549,17 @@ var ts; switch (node.kind) { case 69: return makeUniqueName(node.text); - case 218: - case 217: + case 220: + case 219: return generateNameForModuleOrEnum(node); - case 222: - case 228: + case 224: + case 230: return generateNameForImportOrExportDeclaration(node); - case 213: - case 214: - case 227: + case 215: + case 216: + case 229: return generateNameForExportDefault(); - case 186: + case 188: return generateNameForClassExpression(); } } @@ -25815,289 +26567,14 @@ var ts; var id = ts.getNodeId(node); return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); } - function initializeEmitterWithSourceMaps(jsFilePath, root) { - var sourceMapDir; - var sourceMapSourceIndex = -1; - var sourceMapNameIndexMap = {}; - var sourceMapNameIndices = []; - function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; + function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark) { + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false); } - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - var lastEncodedNameIndex = 0; - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - function base64VLQFormatEncode(inValue) { - function base64FormatEncode(inValue) { - if (inValue < 64) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - var encodedStr = ""; - do { - var currentDigit = inValue & 31; - inValue = inValue >> 5; - if (inValue > 0) { - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; - } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); } - function recordSourceMapSpan(pos) { - var sourceLinePos = ts.computeLineAndCharacterOfPosition(currentLineMap, pos); - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); - if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine !== emittedLine || - lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || - (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && - (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || - (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - nameIndex: getSourceMapNameIndex(), - sourceIndex: sourceMapSourceIndex - }; - } - else { - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - } - function recordEmitNodeStartSpan(node) { - recordSourceMapSpan(ts.skipTrivia(currentText, node.pos)); - } - function recordEmitNodeEndSpan(node) { - recordSourceMapSpan(node.end); - } - function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentText, startPos); - recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); - recordSourceMapSpan(tokenEndPos); - return tokenEndPos; - } - function recordNewSourceFileStart(node) { - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true)); - sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; - sourceMapData.inputSourceFileNames.push(node.fileName); - if (compilerOptions.inlineSources) { - if (!sourceMapData.sourceMapSourcesContent) { - sourceMapData.sourceMapSourcesContent = []; - } - sourceMapData.sourceMapSourcesContent.push(node.text); - } - } - function recordScopeNameOfNode(node, scopeName) { - function recordScopeNameIndex(scopeNameIndex) { - sourceMapNameIndices.push(scopeNameIndex); - } - function recordScopeNameStart(scopeName) { - var scopeNameIndex = -1; - if (scopeName) { - var parentIndex = getSourceMapNameIndex(); - if (parentIndex !== -1) { - var name_22 = node.name; - if (!name_22 || name_22.kind !== 136) { - scopeName = "." + scopeName; - } - scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; - } - scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); - if (scopeNameIndex === undefined) { - scopeNameIndex = sourceMapData.sourceMapNames.length; - sourceMapData.sourceMapNames.push(scopeName); - sourceMapNameIndexMap[scopeName] = scopeNameIndex; - } - } - recordScopeNameIndex(scopeNameIndex); - } - if (scopeName) { - recordScopeNameStart(scopeName); - } - else if (node.kind === 213 || - node.kind === 173 || - node.kind === 143 || - node.kind === 142 || - node.kind === 145 || - node.kind === 146 || - node.kind === 218 || - node.kind === 214 || - node.kind === 217) { - if (node.name) { - var name_23 = node.name; - scopeName = name_23.kind === 136 - ? ts.getTextOfNode(name_23) - : node.name.text; - } - recordScopeNameStart(scopeName); - } - else { - recordScopeNameIndex(getSourceMapNameIndex()); - } - } - function recordScopeNameEnd() { - sourceMapNameIndices.pop(); - } - ; - function writeCommentRangeWithMap(currentText, currentLineMap, writer, comment, newLine) { - recordSourceMapSpan(comment.pos); - ts.writeCommentRange(currentText, currentLineMap, writer, comment, newLine); - recordSourceMapSpan(comment.end); - } - function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) { - if (typeof JSON !== "undefined") { - var map_2 = { - version: version, - file: file, - sourceRoot: sourceRoot, - sources: sources, - names: names, - mappings: mappings - }; - if (sourcesContent !== undefined) { - map_2.sourcesContent = sourcesContent; - } - return JSON.stringify(map_2); - } - return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\" " + (sourcesContent !== undefined ? ",\"sourcesContent\":[" + serializeStringArray(sourcesContent) + "]" : "") + "}"; - function serializeStringArray(list) { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { - if (i) { - output += ","; - } - output += "\"" + ts.escapeString(list[i]) + "\""; - } - return output; - } - } - function writeJavaScriptAndSourceMapFile(emitOutput, jsFilePath, writeByteOrderMark) { - encodeLastRecordedSourceMapSpan(); - var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent); - sourceMapDataList.push(sourceMapData); - var sourceMapUrl; - if (compilerOptions.inlineSourceMap) { - var base64SourceMapText = ts.convertToBase64(sourceMapText); - sourceMapUrl = "//# sourceMappingURL=data:application/json;base64," + base64SourceMapText; - } - else { - ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, false); - sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL; - } - writeJavaScriptFile(emitOutput + sourceMapUrl, jsFilePath, writeByteOrderMark); - } - var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)); - sourceMapData = { - sourceMapFilePath: jsFilePath + ".map", - jsSourceMappingURL: sourceMapJsFile + ".map", - sourceMapFile: sourceMapJsFile, - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapSourcesContent: undefined, - sourceMapDecodedMappings: [] - }; - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (root) { - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); - } - function emitNodeWithSourceMap(node) { - if (node) { - if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node); - } - if (node.kind !== 248) { - recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node); - recordEmitNodeEndSpan(node); - } - else { - recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node); - } - } - } - function emitNodeWithCommentsAndWithSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - writeEmittedFiles = writeJavaScriptAndSourceMapFile; - emit = emitNodeWithCommentsAndWithSourcemap; - emitStart = recordEmitNodeStartSpan; - emitEnd = recordEmitNodeEndSpan; - emitToken = writeTextWithSpanRecord; - scopeEmitStart = recordScopeNameOfNode; - scopeEmitEnd = recordScopeNameEnd; - writeComment = writeCommentRangeWithMap; - } - function writeJavaScriptFile(emitOutput, jsFilePath, writeByteOrderMark) { - ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark); } function createTempVariable(flags) { var result = ts.createSynthesizedNode(69); @@ -26128,7 +26605,9 @@ var ts; write(";"); } } - function emitTokenText(tokenKind, startPos, emitFn) { + function emitToken(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentText, startPos); + emitPos(tokenStartPos); var tokenString = ts.tokenToString(tokenKind); if (emitFn) { emitFn(); @@ -26136,7 +26615,9 @@ var ts; else { write(tokenString); } - return startPos + tokenString.length; + var tokenEndPos = tokenStartPos + tokenString.length; + emitPos(tokenEndPos); + return tokenEndPos; } function emitOptional(prefix, node) { if (node) { @@ -26153,11 +26634,6 @@ var ts; write(")"); } } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { ts.Debug.assert(nodes.length > 0); increaseIndent(); @@ -26323,10 +26799,10 @@ var ts; emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); write("("); emit(tempVariable); - if (node.template.kind === 183) { + if (node.template.kind === 185) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 181 + var needsParens = templateSpan.expression.kind === 183 && templateSpan.expression.operatorToken.kind === 24; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -26350,7 +26826,7 @@ var ts; } for (var i = 0, n = node.templateSpans.length; i < n; i++) { var templateSpan = node.templateSpans[i]; - var needsParens = templateSpan.expression.kind !== 172 + var needsParens = templateSpan.expression.kind !== 174 && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1; if (i > 0 || headEmitted) { write(" + "); @@ -26370,11 +26846,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 168: - case 169: - return parent.expression === template; case 170: + case 171: + return parent.expression === template; case 172: + case 174: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1; @@ -26382,7 +26858,7 @@ var ts; } function comparePrecedenceToBinaryPlus(expression) { switch (expression.kind) { - case 181: + case 183: switch (expression.operatorToken.kind) { case 37: case 39: @@ -26394,8 +26870,8 @@ var ts; default: return -1; } + case 186: case 184: - case 182: return -1; default: return 1; @@ -26418,13 +26894,13 @@ var ts; } } function emitAttributeName(name) { - if (/[A-Za-z_]+[\w*]/.test(name.text)) { - write("\""); + if (/^[A-Za-z_]\w*$/.test(name.text)) { emit(name); - write("\""); } else { + write("\""); emit(name); + write("\""); } } function emitJsxAttribute(node) { @@ -26439,7 +26915,7 @@ var ts; } function emitJsxElement(openingNode, children) { var syntheticReactRef = ts.createSynthesizedNode(69); - syntheticReactRef.text = "React"; + syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; syntheticReactRef.parent = openingNode; emitLeadingComments(openingNode); emitExpressionIdentifier(syntheticReactRef); @@ -26451,12 +26927,12 @@ var ts; } else { var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 239; })) { + if (ts.forEach(attrs, function (attr) { return attr.kind === 241; })) { emitExpressionIdentifier(syntheticReactRef); write(".__spread("); var haveOpenedObjectLiteral = false; for (var i_1 = 0; i_1 < attrs.length; i_1++) { - if (attrs[i_1].kind === 239) { + if (attrs[i_1].kind === 241) { if (i_1 === 0) { write("{}, "); } @@ -26470,7 +26946,7 @@ var ts; emit(attrs[i_1].expression); } else { - ts.Debug.assert(attrs[i_1].kind === 238); + ts.Debug.assert(attrs[i_1].kind === 240); if (haveOpenedObjectLiteral) { write(", "); } @@ -26501,10 +26977,10 @@ var ts; } if (children) { for (var i = 0; i < children.length; i++) { - if (children[i].kind === 240 && !(children[i].expression)) { + if (children[i].kind === 242 && !(children[i].expression)) { continue; } - if (children[i].kind === 236) { + if (children[i].kind === 238) { var text = getTextToEmit(children[i]); if (text !== undefined) { write(", \""); @@ -26521,11 +26997,11 @@ var ts; write(")"); emitTrailingComments(openingNode); } - if (node.kind === 233) { + if (node.kind === 235) { emitJsxElement(node.openingElement, node.children); } else { - ts.Debug.assert(node.kind === 234); + ts.Debug.assert(node.kind === 236); emitJsxElement(node); } } @@ -26547,11 +27023,11 @@ var ts; if (i > 0) { write(" "); } - if (attribs[i].kind === 239) { + if (attribs[i].kind === 241) { emitJsxSpreadAttribute(attribs[i]); } else { - ts.Debug.assert(attribs[i].kind === 238); + ts.Debug.assert(attribs[i].kind === 240); emitJsxAttribute(attribs[i]); } } @@ -26559,11 +27035,11 @@ var ts; function emitJsxOpeningOrSelfClosingElement(node) { write("<"); emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 234)) { + if (node.attributes.length > 0 || (node.kind === 236)) { write(" "); } emitAttributes(node.attributes); - if (node.kind === 234) { + if (node.kind === 236) { write("/>"); } else { @@ -26582,16 +27058,16 @@ var ts; } emitJsxClosingElement(node.closingElement); } - if (node.kind === 233) { + if (node.kind === 235) { emitJsxElement(node); } else { - ts.Debug.assert(node.kind === 234); + ts.Debug.assert(node.kind === 236); emitJsxOpeningOrSelfClosingElement(node); } } function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 163); + ts.Debug.assert(node.kind !== 165); if (node.kind === 9) { emitLiteral(node); } @@ -26626,59 +27102,60 @@ var ts; function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 164: - case 189: - case 181: - case 168: - case 241: - case 136: - case 182: - case 139: - case 175: - case 197: - case 167: - case 227: - case 195: - case 188: - case 199: - case 200: - case 201: - case 196: - case 234: - case 235: - case 239: - case 240: - case 169: - case 172: - case 180: - case 179: - case 204: - case 246: - case 185: - case 206: - case 170: - case 190: - case 208: - case 171: - case 176: - case 177: - case 198: - case 205: - case 184: - return true; - case 163: - case 247: - case 138: - case 245: - case 141: - case 211: - return parent.initializer === node; case 166: - return parent.expression === node; + case 191: + case 183: + case 170: + case 243: + case 136: + case 184: + case 139: + case 177: + case 199: + case 169: + case 229: + case 197: + case 190: + case 201: + case 202: + case 203: + case 198: + case 239: + case 236: + case 237: + case 241: + case 242: + case 171: case 174: + case 182: + case 181: + case 206: + case 248: + case 187: + case 208: + case 172: + case 192: + case 210: case 173: + case 178: + case 179: + case 200: + case 207: + case 186: + return true; + case 165: + case 249: + case 138: + case 247: + case 141: + case 213: + return parent.initializer === node; + case 168: + return parent.expression === node; + case 176: + case 175: return parent.body === node; - case 221: + case 223: return parent.moduleReference === node; case 135: return parent.left === node; @@ -26692,7 +27169,7 @@ var ts; } var container = resolver.getReferencedExportContainer(node); if (container) { - if (container.kind === 248) { + if (container.kind === 250) { if (modulekind !== 5 && modulekind !== 4) { write("exports."); } @@ -26706,15 +27183,15 @@ var ts; if (modulekind !== 5) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { - if (declaration.kind === 223) { + if (declaration.kind === 225) { write(getGeneratedNameForNode(declaration.parent)); write(languageVersion === 0 ? "[\"default\"]" : ".default"); return; } - else if (declaration.kind === 226) { + else if (declaration.kind === 228) { write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_24 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_24); + var name_21 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_21); if (languageVersion === 0 && identifier === "default") { write("[\"default\"]"); } @@ -26745,10 +27222,10 @@ var ts; if (languageVersion < 2) { var parent_6 = node.parent; switch (parent_6.kind) { - case 163: - case 214: - case 217: - case 211: + case 165: + case 216: + case 219: + case 213: return parent_6.name === node && resolver.isNestedRedeclaration(parent_6); } } @@ -26757,8 +27234,8 @@ var ts; function emitIdentifier(node) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_25 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_25); + var name_22 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_22); return; } } @@ -26782,6 +27259,9 @@ var ts; if (resolver.getNodeCheckFlags(node) & 2) { write("_this"); } + else if (convertedLoopState) { + write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); + } else { write("this"); } @@ -26855,10 +27335,10 @@ var ts; } } function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 181 && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { + if (node.parent.kind === 183 && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { return true; } - else if (node.parent.kind === 182 && node.parent.condition === node) { + else if (node.parent.kind === 184 && node.parent.condition === node) { return true; } return false; @@ -26866,11 +27346,11 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 69: - case 164: case 166: - case 167: case 168: - case 172: + case 169: + case 170: + case 174: return false; } return true; @@ -26887,17 +27367,17 @@ var ts; write(", "); } var e = elements[pos]; - if (e.kind === 185) { + if (e.kind === 187) { e = e.expression; emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 166) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 185) { + while (i < length && elements[i].kind !== 187) { i++; } write("["); @@ -26920,7 +27400,7 @@ var ts; } } function isSpreadElementExpression(node) { - return node.kind === 185; + return node.kind === 187; } function emitArrayLiteral(node) { var elements = node.elements; @@ -27032,10 +27512,10 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 245) { + if (property.kind === 247) { emit(property.initializer); } - else if (property.kind === 246) { + else if (property.kind === 248) { emitExpressionIdentifier(property.name); } else if (property.kind === 143) { @@ -27084,35 +27564,35 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(181, startsOnNewLine); + var result = ts.createSynthesizedNode(183, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(166); + var result = ts.createSynthesizedNode(168); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(21); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(167); + var result = ts.createSynthesizedNode(169); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; } function parenthesizeForAccess(expr) { - while (expr.kind === 171 || expr.kind === 189) { + while (expr.kind === 173 || expr.kind === 191) { expr = expr.expression; } if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 169 && + expr.kind !== 171 && expr.kind !== 8) { return expr; } - var node = ts.createSynthesizedNode(172); + var node = ts.createSynthesizedNode(174); node.expression = expr; return node; } @@ -27139,7 +27619,7 @@ var ts; } function isNamespaceExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 248; + return container && container.kind !== 250; } function emitShorthandPropertyAssignment(node) { writeTextOfNode(currentText, node.name); @@ -27157,7 +27637,7 @@ var ts; if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 166 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 168 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -27168,7 +27648,7 @@ var ts; if (compilerOptions.isolatedModules) { return undefined; } - return node.kind === 166 || node.kind === 167 + return node.kind === 168 || node.kind === 169 ? resolver.getConstantValue(node) : undefined; } @@ -27251,6 +27731,9 @@ var ts; case 135: emitQualifiedNameAsExpression(node, useFallback); break; + default: + emitNodeWithoutSourceMap(node); + break; } } function emitIndexedAccess(node) { @@ -27263,10 +27746,10 @@ var ts; write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 185; }); + return ts.forEach(elements, function (e) { return e.kind === 187; }); } function skipParentheses(node) { - while (node.kind === 172 || node.kind === 171 || node.kind === 189) { + while (node.kind === 174 || node.kind === 173 || node.kind === 191) { node = node.expression; } return node; @@ -27287,12 +27770,12 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 166) { + if (expr.kind === 168) { target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 167) { + else if (expr.kind === 169) { target = emitCallTarget(expr.expression); write("["); emit(expr.argumentExpression); @@ -27333,7 +27816,7 @@ var ts; } else { emit(node.expression); - superCall = node.expression.kind === 166 && node.expression.expression.kind === 95; + superCall = node.expression.kind === 168 && node.expression.expression.kind === 95; } if (superCall && languageVersion < 2) { write(".call("); @@ -27384,21 +27867,21 @@ var ts; } } function emitParenExpression(node) { - if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 174) { - if (node.expression.kind === 171 || node.expression.kind === 189) { + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 176) { + if (node.expression.kind === 173 || node.expression.kind === 191) { var operand = node.expression.expression; - while (operand.kind === 171 || operand.kind === 189) { + while (operand.kind === 173 || operand.kind === 191) { operand = operand.expression; } - if (operand.kind !== 179 && + if (operand.kind !== 181 && + operand.kind !== 179 && + operand.kind !== 178 && operand.kind !== 177 && - operand.kind !== 176 && - operand.kind !== 175 && - operand.kind !== 180 && - operand.kind !== 169 && - !(operand.kind === 168 && node.parent.kind === 169) && - !(operand.kind === 173 && node.parent.kind === 168) && - !(operand.kind === 8 && node.parent.kind === 166)) { + operand.kind !== 182 && + operand.kind !== 171 && + !(operand.kind === 170 && node.parent.kind === 171) && + !(operand.kind === 175 && node.parent.kind === 170) && + !(operand.kind === 8 && node.parent.kind === 168)) { emit(operand); return; } @@ -27427,21 +27910,22 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 211 || node.parent.kind === 163); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 213 || node.parent.kind === 165); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, true); } function emitPrefixUnaryExpression(node) { - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); + var exportChanged = (node.operator === 41 || node.operator === 42) && + isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); if (exportChanged) { write(exportFunctionForFile + "(\""); emitNodeWithoutSourceMap(node.operand); write("\", "); } write(ts.tokenToString(node.operator)); - if (node.operand.kind === 179) { + if (node.operand.kind === 181) { var operand = node.operand; if (node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) { write(" "); @@ -27484,10 +27968,10 @@ var ts; } var current = node; while (current) { - if (current.kind === 248) { + if (current.kind === 250) { return !isExported || ((ts.getCombinedNodeFlags(node) & 2) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 219) { + else if (ts.isFunctionLike(current) || current.kind === 221) { return false; } else { @@ -27503,7 +27987,7 @@ var ts; if (ts.isElementAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(167, false); + synthesizedLHS = ts.createSynthesizedNode(169, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; if (leftHandSideExpression.argumentExpression.kind !== 8 && @@ -27520,7 +28004,7 @@ var ts; else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(166, false); + synthesizedLHS = ts.createSynthesizedNode(168, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; synthesizedLHS.dotToken = leftHandSideExpression.dotToken; @@ -27548,8 +28032,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 && node.operatorToken.kind === 56 && - (node.left.kind === 165 || node.left.kind === 164)) { - emitDestructuring(node, node.parent.kind === 195); + (node.left.kind === 167 || node.left.kind === 166)) { + emitDestructuring(node, node.parent.kind === 197); } else { var exportChanged = node.operatorToken.kind >= 56 && @@ -27601,7 +28085,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 192) { + if (node && node.kind === 194) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -27615,22 +28099,20 @@ var ts; } emitToken(15, node.pos); increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 219) { - ts.Debug.assert(node.parent.kind === 218); + if (node.kind === 221) { + ts.Debug.assert(node.parent.kind === 220); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 219) { + if (node.kind === 221) { emitTempDeclarations(true); } decreaseIndent(); writeLine(); emitToken(16, node.statements.end); - scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 192) { + if (node.kind === 194) { write(" "); emit(node); } @@ -27642,7 +28124,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 174); + emitParenthesizedIf(node.expression, node.expression.kind === 176); write(";"); } function emitIfStatement(node) { @@ -27655,7 +28137,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(80, node.thenStatement.end); - if (node.elseStatement.kind === 196) { + if (node.elseStatement.kind === 198) { write(" "); emit(node.elseStatement); } @@ -27675,7 +28157,7 @@ var ts; else { emitNormalLoopBody(node, true); } - if (node.statement.kind === 192) { + if (node.statement.kind === 194) { write(" "); } else { @@ -27766,7 +28248,7 @@ var ts; } else { var loop = convertLoopBody(node); - if (node.parent.kind === 207) { + if (node.parent.kind === 209) { emitLabelAndColon(node.parent); } loopEmitter(node, loop); @@ -27776,10 +28258,10 @@ var ts; var functionName = makeUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 199: - case 200: case 201: - if (node.initializer.kind === 212) { + case 202: + case 203: + if (node.initializer.kind === 214) { loopInitializer = node.initializer; } break; @@ -27792,7 +28274,7 @@ var ts; collectNames(varDeclaration.name); } } - var bodyIsBlock = node.statement.kind === 192; + var bodyIsBlock = node.statement.kind === 194; var paramList = loopParameters ? loopParameters.join(", ") : ""; writeLine(); write("var " + functionName + " = function(" + paramList + ")"); @@ -27807,6 +28289,9 @@ var ts; if (convertedOuterLoopState.argumentsName) { convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; } + if (convertedOuterLoopState.thisName) { + convertedLoopState.thisName = convertedOuterLoopState.thisName; + } if (convertedOuterLoopState.hoistedLocalVariables) { convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; } @@ -27828,6 +28313,15 @@ var ts; writeLine(); } } + if (convertedLoopState.thisName) { + if (convertedOuterLoopState) { + convertedOuterLoopState.thisName = convertedLoopState.thisName; + } + else { + write("var " + convertedLoopState.thisName + " = this;"); + writeLine(); + } + } if (convertedLoopState.hoistedLocalVariables) { if (convertedOuterLoopState) { convertedOuterLoopState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; @@ -27877,7 +28371,7 @@ var ts; if (emitAsEmbeddedStatement) { emitEmbeddedStatement(node.statement); } - else if (node.statement.kind === 192) { + else if (node.statement.kind === 194) { emitLines(node.statement.statements); } else { @@ -27973,7 +28467,7 @@ var ts; var endPos = emitToken(86, node.pos); write(" "); endPos = emitToken(17, endPos); - if (node.initializer && node.initializer.kind === 212) { + if (node.initializer && node.initializer.kind === 214) { var variableDeclarationList = node.initializer; var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); if (startIsEmitted) { @@ -27999,7 +28493,7 @@ var ts; } } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 && node.kind === 201) { + if (languageVersion < 2 && node.kind === 203) { emitLoop(node, emitDownLevelForOfStatementWorker); } else { @@ -28010,7 +28504,7 @@ var ts; var endPos = emitToken(86, node.pos); write(" "); endPos = emitToken(17, endPos); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 214) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); @@ -28020,7 +28514,7 @@ var ts; else { emit(node.initializer); } - if (node.kind === 200) { + if (node.kind === 202) { write(" in "); } else { @@ -28035,9 +28529,6 @@ var ts; emitNormalLoopBody(node, true); } } - function emitDownLevelForOfStatement(node) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } function emitDownLevelForOfStatementWorker(node, loop) { var endPos = emitToken(86, node.pos); write(" "); @@ -28076,7 +28567,7 @@ var ts; increaseIndent(); var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 214) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -28098,7 +28589,7 @@ var ts; } else { var assignmentExpression = createBinaryExpression(node.initializer, 56, rhsIterationValue, false); - if (node.initializer.kind === 164 || node.initializer.kind === 165) { + if (node.initializer.kind === 166 || node.initializer.kind === 167) { emitDestructuring(assignmentExpression, true, undefined); } else { @@ -28120,12 +28611,12 @@ var ts; } function emitBreakOrContinueStatement(node) { if (convertedLoopState) { - var jump = node.kind === 203 ? 2 : 4; + var jump = node.kind === 205 ? 2 : 4; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { if (!node.label) { - if (node.kind === 203) { + if (node.kind === 205) { convertedLoopState.nonLocalJumps |= 2; write("return \"break\";"); } @@ -28136,7 +28627,7 @@ var ts; } else { var labelMarker; - if (node.kind === 203) { + if (node.kind === 205) { labelMarker = "break-" + node.label.text; setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); } @@ -28149,7 +28640,7 @@ var ts; return; } } - emitToken(node.kind === 203 ? 70 : 75, node.pos); + emitToken(node.kind === 205 ? 70 : 75, node.pos); emitOptional(" ", node.label); write(";"); } @@ -28214,7 +28705,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 241) { + if (node.kind === 243) { write("case "); emit(node.expression); write(":"); @@ -28283,7 +28774,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 218); + } while (node && node.kind !== 220); return node; } function emitContainingModuleName(node) { @@ -28308,20 +28799,20 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(8); zero.text = "0"; - var result = ts.createSynthesizedNode(177); + var result = ts.createSynthesizedNode(179); result.expression = zero; return result; } function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 248) { - ts.Debug.assert(!!(node.flags & 512) || node.kind === 227); + if (node.parent.kind === 250) { + ts.Debug.assert(!!(node.flags & 512) || node.kind === 229); if (modulekind === 1 || modulekind === 2 || modulekind === 3) { if (!isEs6Module) { - if (languageVersion === 1) { + if (languageVersion !== 0) { write("Object.defineProperty(exports, \"__esModule\", { value: true });"); writeLine(); } - else if (languageVersion === 0) { + else { write("exports.__esModule = true;"); writeLine(); } @@ -28409,7 +28900,7 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(name); write("\", "); } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 || name.parent.kind === 163); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 213 || name.parent.kind === 165); if (isVariableDeclarationOrBindingElement) { emitModuleMemberName(name.parent); } @@ -28433,7 +28924,7 @@ var ts; function emitDestructuring(root, isAssignmentExpressionStatement, value) { var emitCount = 0; var canDefineTempVariablesInPlace = false; - if (root.kind === 211) { + if (root.kind === 213) { var isExported = ts.getCombinedNodeFlags(root) & 2; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; @@ -28441,7 +28932,7 @@ var ts; else if (root.kind === 138) { canDefineTempVariablesInPlace = true; } - if (root.kind === 181) { + if (root.kind === 183) { emitAssignmentExpression(root); } else { @@ -28458,14 +28949,14 @@ var ts; } function createDefaultValueCheck(value, defaultValue) { value = ensureIdentifier(value, true); - var equals = ts.createSynthesizedNode(181); + var equals = ts.createSynthesizedNode(183); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(32); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(182); + var cond = ts.createSynthesizedNode(184); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(53); cond.whenTrue = whenTrue; @@ -28493,7 +28984,7 @@ var ts; : createElementAccessExpression(object, index); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(168); + var call = ts.createSynthesizedNode(170); var sliceIdentifier = ts.createSynthesizedNode(69); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -28508,9 +28999,9 @@ var ts; } for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { var p = properties_5[_a]; - if (p.kind === 245 || p.kind === 246) { + if (p.kind === 247 || p.kind === 248) { var propName = p.name; - var target_1 = p.kind === 246 ? p : p.initializer || propName; + var target_1 = p.kind === 248 ? p : p.initializer || propName; emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName)); } } @@ -28522,8 +29013,8 @@ var ts; } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187) { - if (e.kind !== 185) { + if (e.kind !== 189) { + if (e.kind !== 187) { emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); } else if (i === elements.length - 1) { @@ -28533,20 +29024,20 @@ var ts; } } function emitDestructuringAssignment(target, value) { - if (target.kind === 246) { + if (target.kind === 248) { if (target.objectAssignmentInitializer) { value = createDefaultValueCheck(value, target.objectAssignmentInitializer); } target = target.name; } - else if (target.kind === 181 && target.operatorToken.kind === 56) { + else if (target.kind === 183 && target.operatorToken.kind === 56) { value = createDefaultValueCheck(value, target.right); target = target.left; } - if (target.kind === 165) { + if (target.kind === 167) { emitObjectLiteralAssignment(target, value); } - else if (target.kind === 164) { + else if (target.kind === 166) { emitArrayLiteralAssignment(target, value); } else { @@ -28564,14 +29055,14 @@ var ts; emitDestructuringAssignment(target, value); } else { - if (root.parent.kind !== 172) { + if (root.parent.kind !== 174) { write("("); } value = ensureIdentifier(value, true); emitDestructuringAssignment(target, value); write(", "); emit(value); - if (root.parent.kind !== 172) { + if (root.parent.kind !== 174) { write(")"); } } @@ -28592,11 +29083,11 @@ var ts; } for (var i = 0; i < numElements; i++) { var element = elements[i]; - if (pattern.kind === 161) { + if (pattern.kind === 163) { var propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } - else if (element.kind !== 187) { + else if (element.kind !== 189) { if (!element.dotDotDotToken) { emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); } @@ -28628,8 +29119,8 @@ var ts; var isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & 16384) && (getCombinedFlagsForIdentifier(node.name) & 8192); if (isLetDefinedInLoop && - node.parent.parent.kind !== 200 && - node.parent.parent.kind !== 201) { + node.parent.parent.kind !== 202 && + node.parent.parent.kind !== 203) { initializer = createVoidZero(); } } @@ -28647,7 +29138,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 187) { + if (node.kind === 189) { return; } var name = node.name; @@ -28659,7 +29150,7 @@ var ts; } } function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 211 && node.parent.kind !== 163)) { + if (!node.parent || (node.parent.kind !== 213 && node.parent.kind !== 165)) { return 0; } return ts.getCombinedNodeFlags(node.parent); @@ -28667,7 +29158,7 @@ var ts; function isES6ExportedDeclaration(node) { return !!(node.flags & 2) && modulekind === 5 && - node.parent.kind === 248; + node.parent.kind === 250; } function emitVariableStatement(node) { var startIsEmitted = false; @@ -28712,12 +29203,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_26 = createTempVariable(0); + var name_23 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_26); - emit(name_26); + tempParameters.push(name_23); + emit(name_23); } else { emit(node.name); @@ -28821,7 +29312,7 @@ var ts; emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 174 && languageVersion >= 2; + return node.kind === 176 && languageVersion >= 2; } function emitDeclarationName(node) { if (node.name) { @@ -28832,20 +29323,24 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 173) { + if (node.kind === 175) { return !!node.name; } - if (node.kind === 213) { - return !!node.name || languageVersion < 2; + if (node.kind === 215) { + return !!node.name || modulekind !== 5; } } function emitFunctionDeclaration(node) { if (ts.nodeIsMissing(node.body)) { return emitCommentsOnNotEmittedNode(node); } - if (node.kind !== 143 && node.kind !== 142 && - node.parent && node.parent.kind !== 245 && - node.parent.kind !== 168) { + var kind = node.kind, parent = node.parent; + if (kind !== 143 && + kind !== 142 && + parent && + parent.kind !== 247 && + parent.kind !== 170 && + parent.kind !== 166) { emitLeadingComments(node); } emitStart(node); @@ -28866,11 +29361,11 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (modulekind !== 5 && node.kind === 213 && node.parent === currentSourceFile && node.name) { + if (modulekind !== 5 && kind === 215 && parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } emitEnd(node); - if (node.kind !== 143 && node.kind !== 142) { + if (kind !== 143 && kind !== 142) { emitTrailingComments(node); } } @@ -28902,7 +29397,7 @@ var ts; } function emitAsyncFunctionBodyForES6(node) { var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 174; + var isArrowFunction = node.kind === 176; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096) !== 0; if (!isArrowFunction) { write(" {"); @@ -28912,17 +29407,16 @@ var ts; } write(" __awaiter(this"); if (hasLexicalArguments) { - write(", arguments"); + write(", arguments, "); } else { - write(", void 0"); + write(", void 0, "); } if (promiseConstructor) { - write(", "); - emitNodeWithoutSourceMap(promiseConstructor); + emitEntityNameAsExpression(promiseConstructor, false); } else { - write(", Promise"); + write("Promise"); } if (hasLexicalArguments) { write(", function* (_arguments)"); @@ -28944,7 +29438,7 @@ var ts; write(" { }"); } else { - if (node.body.kind === 192) { + if (node.body.kind === 194) { emitBlockFunctionBody(node, node.body); } else { @@ -28969,7 +29463,7 @@ var ts; emitSignatureParameters(node); } var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync && languageVersion === 2) { + if (isAsync) { emitAsyncFunctionBodyForES6(node); } else { @@ -28996,14 +29490,13 @@ var ts; } write(" "); var current = body; - while (current.kind === 171) { + while (current.kind === 173) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 165); + emitParenthesizedIf(body, current.kind === 167); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); emitDetachedCommentsAndUpdateCommentsInfo(node.body); @@ -29024,8 +29517,10 @@ var ts; increaseIndent(); writeLine(); emitLeadingComments(node.body); + emitStart(body); write("return "); emit(body); + emitEnd(body); write(";"); emitTrailingComments(node.body); emitTempDeclarations(true); @@ -29035,11 +29530,9 @@ var ts; emitStart(node.body); write("}"); emitEnd(node.body); - scopeEmitEnd(); } function emitBlockFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); emitDetachedCommentsAndUpdateCommentsInfo(body.statements); @@ -29066,14 +29559,13 @@ var ts; decreaseIndent(); } emitToken(16, body.statements.end); - scopeEmitEnd(); } function findInitialSuperCall(ctor) { if (ctor.body) { var statement = ctor.body.statements[0]; - if (statement && statement.kind === 195) { + if (statement && statement.kind === 197) { var expr = statement.expression; - if (expr && expr.kind === 168) { + if (expr && expr.kind === 170) { var func = expr.expression; if (func && func.kind === 95) { return statement; @@ -29156,7 +29648,7 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 191) { + if (member.kind === 193) { writeLine(); write(";"); } @@ -29253,7 +29745,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 191) { + else if (member.kind === 193) { writeLine(); write(";"); } @@ -29314,7 +29806,6 @@ var ts; } var startIndex = 0; write(" {"); - scopeEmitStart(node, "constructor"); increaseIndent(); if (ctor) { startIndex = emitDirectivePrologues(ctor.body.statements, true); @@ -29362,7 +29853,6 @@ var ts; } decreaseIndent(); emitToken(16, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); emitEnd(ctor || node); if (ctor) { emitTrailingComments(ctor); @@ -29387,7 +29877,7 @@ var ts; } function emitClassLikeDeclarationForES6AndHigher(node) { var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 214) { + if (node.kind === 216) { if (thisNodeIsDecorated) { if (isES6ExportedDeclaration(node) && !(node.flags & 512)) { write("export "); @@ -29404,7 +29894,7 @@ var ts; } } var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 186; + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 188; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0); @@ -29414,7 +29904,7 @@ var ts; write(" = "); } write("class"); - if ((node.name || (node.flags & 512 && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if ((node.name || (node.flags & 512 && (staticProperties.length > 0 || modulekind !== 5))) && !thisNodeIsDecorated) { write(" "); emitDeclarationName(node); } @@ -29425,14 +29915,12 @@ var ts; } write(" {"); increaseIndent(); - scopeEmitStart(node); writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES6AndHigher(node); decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); if (thisNodeIsDecorated) { write(";"); } @@ -29454,24 +29942,34 @@ var ts; emitPropertyDeclarations(node, staticProperties); emitDecoratorsOfClass(node); } - if (!isES6ExportedDeclaration(node) && (node.flags & 2)) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); + if (!(node.flags & 2)) { + return; } - else if (isES6ExportedDeclaration(node) && (node.flags & 512) && thisNodeIsDecorated) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); + if (modulekind !== 5) { + emitExportMemberAssignment(node); + } + else { + if (node.flags & 512) { + if (thisNodeIsDecorated) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } + } + else if (node.parent.kind !== 250) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emitDeclarationName(node); + emitEnd(node); + write(";"); + } } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 214) { + if (node.kind === 216) { if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -29495,7 +29993,6 @@ var ts; tempParameters = undefined; computedPropertyNamesToGeneratedNames = undefined; increaseIndent(); - scopeEmitStart(node); if (baseTypeNode) { writeLine(); emitStart(baseTypeNode); @@ -29526,18 +30023,17 @@ var ts; decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); emitStart(node); - write(")("); + write("("); if (baseTypeNode) { emit(baseTypeNode.expression); } - write(")"); - if (node.kind === 214) { + write("))"); + if (node.kind === 216) { write(";"); } emitEnd(node); - if (node.kind === 214) { + if (node.kind === 216) { emitExportMemberAssignment(node); } } @@ -29555,30 +30051,29 @@ var ts; function emitDecoratorsOfConstructor(node) { var decorators = node.decorators; var constructor = ts.getFirstConstructorWithBody(node); - var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated); - if (!decorators && !hasDecoratedParameters) { + var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); + if (!decorators && !firstParameterDecorator) { return; } writeLine(); - emitStart(node); + emitStart(node.decorators || firstParameterDecorator); emitDeclarationName(node); write(" = __decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); + } emitSerializedTypeMetadata(node, argumentsWritten >= 0); decreaseIndent(); writeLine(); write("], "); emitDeclarationName(node); - write(");"); - emitEnd(node); + write(")"); + emitEnd(node.decorators || firstParameterDecorator); + write(";"); writeLine(); } function emitDecoratorsOfMembers(node, staticFlag) { @@ -29590,9 +30085,6 @@ var ts; if (!ts.nodeCanBeDecorated(member)) { continue; } - if (!ts.nodeOrChildIsDecorated(member)) { - continue; - } var decorators = void 0; var functionLikeMember = void 0; if (ts.isAccessor(member)) { @@ -29612,27 +30104,27 @@ var ts; functionLikeMember = member; } } + var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); + if (!decorators && !firstParameterDecorator) { + continue; + } writeLine(); - emitStart(member); + emitStart(decorators || firstParameterDecorator); write("__decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + } emitSerializedTypeMetadata(member, argumentsWritten > 0); decreaseIndent(); writeLine(); write("], "); - emitStart(member.name); emitClassMemberPrefix(node, member); write(", "); emitExpressionForPropertyName(member.name); - emitEnd(member.name); if (languageVersion > 0) { if (member.kind !== 141) { write(", null"); @@ -29641,8 +30133,9 @@ var ts; write(", void 0"); } } - write(");"); - emitEnd(member); + write(")"); + emitEnd(decorators || firstParameterDecorator); + write(";"); writeLine(); } } @@ -29655,15 +30148,13 @@ var ts; if (ts.nodeIsDecorated(parameter)) { var decorators = parameter.decorators; argumentsWritten += emitList(decorators, 0, decorators.length, true, false, leadingComma, true, function (decorator) { - emitStart(decorator); write("__param(" + parameterIndex + ", "); emit(decorator.expression); write(")"); - emitEnd(decorator); }); leadingComma = true; } - ++parameterIndex; + parameterIndex++; } } return argumentsWritten; @@ -29687,7 +30178,7 @@ var ts; } function shouldEmitParamTypesMetadata(node) { switch (node.kind) { - case 214: + case 216: case 143: case 146: return true; @@ -29696,7 +30187,7 @@ var ts; } function emitSerializedTypeOfNode(node) { switch (node.kind) { - case 214: + case 216: write("Function"); return; case 141: @@ -29740,7 +30231,7 @@ var ts; write("Boolean"); return; case 130: - case 9: + case 162: write("String"); return; case 128: @@ -29757,6 +30248,7 @@ var ts; case 158: case 159: case 117: + case 161: break; default: ts.Debug.fail("Cannot serialize unexpected type node."); @@ -29770,8 +30262,7 @@ var ts; while (ts.isDeclaration(location) || ts.isTypeNode(location)) { location = location.parent; } - var typeName = ts.cloneEntityName(node.typeName); - typeName.parent = location; + var typeName = ts.cloneEntityName(node.typeName, location); var result = resolver.getTypeReferenceSerializationKind(typeName); switch (result) { case ts.TypeReferenceSerializationKind.Unknown: @@ -29821,7 +30312,7 @@ var ts; function emitSerializedParameterTypesOfNode(node) { if (node) { var valueDeclaration; - if (node.kind === 214) { + if (node.kind === 216) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -29911,9 +30402,10 @@ var ts; return; } if (!shouldHoistDeclarationInSystemJsModule(node)) { - if (!(node.flags & 2) || isES6ExportedDeclaration(node)) { + var isES6ExportedEnum = isES6ExportedDeclaration(node); + if (!(node.flags & 2) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 219))) { emitStart(node); - if (isES6ExportedDeclaration(node)) { + if (isES6ExportedEnum) { write("export "); } write("var "); @@ -29930,12 +30422,10 @@ var ts; emitEnd(node.name); write(") {"); increaseIndent(); - scopeEmitStart(node); emitLines(node.members); decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); write(")("); emitModuleMemberName(node); write(" || ("); @@ -29993,7 +30483,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 218) { + if (moduleDeclaration.body.kind === 220) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -30004,6 +30494,9 @@ var ts; function isModuleMergedWithES6Class(node) { return languageVersion === 2 && !!(resolver.getNodeCheckFlags(node) & 32768); } + function isFirstDeclarationOfKind(node, declarations, kind) { + return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); + } function emitModuleDeclaration(node) { var shouldEmit = shouldEmitModuleDeclaration(node); if (!shouldEmit) { @@ -30012,15 +30505,18 @@ var ts; var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); if (emitVarForModule) { - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); + var isES6ExportedNamespace = isES6ExportedDeclaration(node); + if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 220)) { + emitStart(node); + if (isES6ExportedNamespace) { + write("export "); + } + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); } emitStart(node); write("(function ("); @@ -30028,7 +30524,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 219) { + if (node.body.kind === 221) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; @@ -30044,7 +30540,6 @@ var ts; else { write("{"); increaseIndent(); - scopeEmitStart(node); emitCaptureThisForNodeIfNecessary(node); writeLine(); emit(node.body); @@ -30052,7 +30547,6 @@ var ts; writeLine(); var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; emitToken(16, moduleBlock.statements.end); - scopeEmitEnd(); } write(")("); if ((node.flags & 2) && !isES6ExportedDeclaration(node)) { @@ -30101,16 +30595,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 221) { + if (node.kind === 223) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 226) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 222 && node.importClause && !!node.importClause.name; + return node.kind === 224 && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -30137,7 +30631,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 224) { + if (node.importClause.namedBindings.kind === 226) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -30163,7 +30657,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 && (node.flags & 2) !== 0; + var isExportedImport = node.kind === 223 && (node.flags & 2) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (modulekind !== 2) { emitLeadingComments(node); @@ -30175,7 +30669,7 @@ var ts; write(" = "); } else { - var isNakedImport = 222 && !node.importClause; + var isNakedImport = 224 && !node.importClause; if (!isNakedImport) { write("var "); write(getGeneratedNameForNode(node)); @@ -30282,15 +30776,17 @@ var ts; } } else { - writeLine(); - write("__export("); - if (modulekind !== 2) { - emitRequire(ts.getExternalModuleName(node)); + if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + writeLine(); + write("__export("); + if (modulekind !== 2) { + emitRequire(ts.getExternalModuleName(node)); + } + else { + write(generatedName); + } + write(");"); } - else { - write(generatedName); - } - write(");"); } emitEnd(node); } @@ -30340,8 +30836,8 @@ var ts; write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 213 && - expression.kind !== 214) { + if (expression.kind !== 215 && + expression.kind !== 216) { write(";"); } emitEnd(node); @@ -30374,26 +30870,28 @@ var ts; externalImports = []; exportSpecifiers = {}; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 222: + case 224: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, true)) { externalImports.push(node); } break; - case 221: - if (node.moduleReference.kind === 232 && resolver.isReferencedAliasDeclaration(node)) { + case 223: + if (node.moduleReference.kind === 234 && resolver.isReferencedAliasDeclaration(node)) { externalImports.push(node); } break; - case 228: + case 230: if (node.moduleSpecifier) { if (!node.exportClause) { - externalImports.push(node); - hasExportStars = true; + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } } else if (resolver.isValueAliasDeclaration(node)) { externalImports.push(node); @@ -30402,12 +30900,12 @@ var ts; else { for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_27 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_27] || (exportSpecifiers[name_27] = [])).push(specifier); + var name_24 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_24] || (exportSpecifiers[name_24] = [])).push(specifier); } } break; - case 227: + case 229: if (node.isExportEquals && !exportEquals) { exportEquals = node; } @@ -30416,7 +30914,7 @@ var ts; } } function emitExportStarHelper() { - if (hasExportStars) { + if (hasExportStarsToExportValues) { writeLine(); write("function __export(m) {"); increaseIndent(); @@ -30432,14 +30930,20 @@ var ts; if (namespaceDeclaration && !isDefaultImport(node)) { return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); } - if (node.kind === 222 && node.importClause) { + if (node.kind === 224 && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 228 && node.moduleSpecifier) { + if (node.kind === 230 && node.moduleSpecifier) { return getGeneratedNameForNode(node); } } - function getExternalModuleNameText(importNode) { + function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { + if (emitRelativePathAsModuleName) { + var name_25 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_25) { + return "\"" + name_25 + "\""; + } + } var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9) { return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); @@ -30454,8 +30958,8 @@ var ts; var started = false; for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { var importNode = externalImports_1[_a]; - var skipNode = importNode.kind === 228 || - (importNode.kind === 222 && !importNode.importClause); + var skipNode = importNode.kind === 230 || + (importNode.kind === 224 && !importNode.importClause); if (skipNode) { continue; } @@ -30473,14 +30977,14 @@ var ts; } } function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) { - if (!hasExportStars) { + if (!hasExportStarsToExportValues) { return undefined; } if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; - if (externalImport.kind === 228 && externalImport.exportClause) { + if (externalImport.kind === 230 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -30495,7 +30999,7 @@ var ts; increaseIndent(); var started = false; if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; ++i) { + for (var i = 0; i < exportedDeclarations.length; i++) { writeExportedName(exportedDeclarations[i]); } } @@ -30509,7 +31013,7 @@ var ts; } for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 228) { + if (externalImport.kind !== 230) { continue; } var exportDecl = externalImport; @@ -30581,13 +31085,13 @@ var ts; writeLine(); write("var "); var seen = {}; - for (var i = 0; i < hoistedVars.length; ++i) { + for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_28 = local.kind === 69 + var name_26 = local.kind === 69 ? local : local.name; - if (name_28) { - var text = ts.unescapeIdentifier(name_28.text); + if (name_26) { + var text = ts.unescapeIdentifier(name_26.text); if (ts.hasProperty(seen, text)) { continue; } @@ -30598,7 +31102,7 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 214 || local.kind === 218 || local.kind === 217) { + if (local.kind === 216 || local.kind === 220 || local.kind === 219) { emitDeclarationName(local); } else { @@ -30632,21 +31136,21 @@ var ts; if (node.flags & 4) { return; } - if (node.kind === 213) { + if (node.kind === 215) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 214) { + if (node.kind === 216) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 217) { + if (node.kind === 219) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -30655,7 +31159,7 @@ var ts; } return; } - if (node.kind === 218) { + if (node.kind === 220) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -30664,17 +31168,17 @@ var ts; } return; } - if (node.kind === 211 || node.kind === 163) { + if (node.kind === 213 || node.kind === 165) { if (shouldHoistVariable(node, false)) { - var name_29 = node.name; - if (name_29.kind === 69) { + var name_27 = node.name; + if (name_27.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_29); + hoistedVars.push(name_27); } else { - ts.forEachChild(name_29, visit); + ts.forEachChild(name_27, visit); } } return; @@ -30700,7 +31204,7 @@ var ts; return false; } return (ts.getCombinedNodeFlags(node) & 24576) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 248; + ts.getEnclosingBlockScopeContainer(node).kind === 250; } function isCurrentFileSystemExternalModule() { return modulekind === 4 && isCurrentFileExternalModule; @@ -30724,7 +31228,7 @@ var ts; } function emitSetters(exportStarFunction, dependencyGroups) { write("setters:["); - for (var i = 0; i < dependencyGroups.length; ++i) { + for (var i = 0; i < dependencyGroups.length; i++) { if (i !== 0) { write(","); } @@ -30738,24 +31242,24 @@ var ts; var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { - case 222: + case 224: if (!entry.importClause) { break; } - case 221: + case 223: ts.Debug.assert(importVariableName !== ""); writeLine(); write(importVariableName + " = " + parameterName + ";"); writeLine(); break; - case 228: + case 230: ts.Debug.assert(importVariableName !== ""); if (entry.exportClause) { writeLine(); write(exportFunctionForFile + "({"); writeLine(); increaseIndent(); - for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) { + for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; i_2++) { if (i_2 !== 0) { write(","); writeLine(); @@ -30789,13 +31293,13 @@ var ts; write("execute: function() {"); increaseIndent(); writeLine(); - for (var i = startIndex; i < node.statements.length; ++i) { + for (var i = startIndex; i < node.statements.length; i++) { var statement = node.statements[i]; switch (statement.kind) { - case 213: - case 222: + case 215: + case 224: continue; - case 228: + case 230: if (!statement.moduleSpecifier) { for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { var element = _b[_a]; @@ -30803,7 +31307,7 @@ var ts; } } continue; - case 221: + case 223: if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { continue; } @@ -30832,8 +31336,8 @@ var ts; write("["); var groupIndices = {}; var dependencyGroups = []; - for (var i = 0; i < externalImports.length; ++i) { - var text = getExternalModuleNameText(externalImports[i]); + for (var i = 0; i < externalImports.length; i++) { + var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); if (ts.hasProperty(groupIndices, text)) { var groupIndex = groupIndices[text]; dependencyGroups[groupIndex].push(externalImports[i]); @@ -30846,18 +31350,12 @@ var ts; if (i !== 0) { write(", "); } - if (emitRelativePathAsModuleName) { - var name_30 = getExternalModuleNameFromDeclaration(host, resolver, externalImports[i]); - if (name_30) { - text = "\"" + name_30 + "\""; - } - } write(text); } write("], function(" + exportFunctionForFile + ") {"); writeLine(); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, true); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitSystemModuleBody(node, dependencyGroups, startIndex); @@ -30881,13 +31379,7 @@ var ts; } for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { var importNode = externalImports_4[_c]; - var externalModuleName = getExternalModuleNameText(importNode); - if (emitRelativePathAsModuleName) { - var name_31 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_31) { - externalModuleName = "\"" + name_31 + "\""; - } - } + var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); var importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { aliasedModuleNames.push(externalModuleName); @@ -30935,7 +31427,7 @@ var ts; writeModuleName(node, emitRelativePathAsModuleName); emitAMDDependencies(node, true, emitRelativePathAsModuleName); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -30946,7 +31438,7 @@ var ts; write("});"); } function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, false); + var startIndex = emitDirectivePrologues(node.statements, false, true); emitEmitHelpers(node); collectExternalModuleInfo(node); emitExportStarHelper(); @@ -30965,7 +31457,7 @@ var ts; writeLines(" }\n})("); emitAMDFactoryHeader(dependencyNames); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -30979,7 +31471,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; var startIndex = emitDirectivePrologues(node.statements, false); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); @@ -31035,7 +31527,8 @@ var ts; if (result) { result = result.replace(/&(\w+);/g, function (s, m) { if (entities[m] !== undefined) { - return String.fromCharCode(entities[m]); + var ch = String.fromCharCode(entities[m]); + return ch === "\"" ? "\\\"" : ch; } else { return s; @@ -31087,23 +31580,40 @@ var ts; } } } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { + function isUseStrictPrologue(node) { + return !!node.expression.text.match(/use strict/); + } + function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { + if (writeUseStrict) { + if (startWithNewLine) { + writeLine(); + } + write("\"use strict\";"); + } + } + function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { + var foundUseStrict = false; + for (var i = 0; i < statements.length; i++) { if (ts.isPrologueDirective(statements[i])) { + if (isUseStrictPrologue(statements[i])) { + foundUseStrict = true; + } if (startWithNewLine || i > 0) { writeLine(); } emit(statements[i]); } else { + ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); return i; } } + ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); return statements.length; } function writeLines(text) { var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; ++i) { + for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (line.length) { writeLine(); @@ -31139,7 +31649,7 @@ var ts; emitShebang(); emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - if (root || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { + if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1]; emitModule(node); } @@ -31152,7 +31662,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -31160,6 +31670,9 @@ var ts; } emitLeadingComments(node.endOfFileToken); } + function emit(node) { + emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); + } function emitNodeWithCommentsAndWithoutSourcemap(node) { emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); } @@ -31181,6 +31694,13 @@ var ts; } } } + function emitNodeWithSourceMap(node) { + if (node) { + emitStart(node); + emitNodeWithoutSourceMap(node); + emitEnd(node); + } + } function emitNodeWithoutSourceMap(node) { if (node) { emitJavaScriptWorker(node); @@ -31188,28 +31708,28 @@ var ts; } function isSpecializedCommentHandling(node) { switch (node.kind) { + case 217: case 215: - case 213: - case 222: - case 221: - case 216: - case 227: + case 224: + case 223: + case 218: + case 229: return true; } } function shouldEmitLeadingAndTrailingComments(node) { switch (node.kind) { - case 193: + case 195: return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 218: + case 220: return shouldEmitModuleDeclaration(node); - case 217: + case 219: return shouldEmitEnumDeclaration(node); } ts.Debug.assert(!isSpecializedCommentHandling(node)); - if (node.kind !== 192 && + if (node.kind !== 194 && node.parent && - node.parent.kind === 174 && + node.parent.kind === 176 && node.parent.body === node && compilerOptions.target <= 1) { return false; @@ -31246,142 +31766,142 @@ var ts; case 13: case 14: return emitLiteral(node); - case 183: + case 185: return emitTemplateExpression(node); - case 190: + case 192: return emitTemplateSpan(node); - case 233: - case 234: - return emitJsxElement(node); + case 235: case 236: + return emitJsxElement(node); + case 238: return emitJsxText(node); - case 240: + case 242: return emitJsxExpression(node); case 135: return emitQualifiedName(node); - case 161: - return emitObjectBindingPattern(node); - case 162: - return emitArrayBindingPattern(node); case 163: - return emitBindingElement(node); + return emitObjectBindingPattern(node); case 164: - return emitArrayLiteral(node); + return emitArrayBindingPattern(node); case 165: + return emitBindingElement(node); + case 166: + return emitArrayLiteral(node); + case 167: return emitObjectLiteral(node); - case 245: + case 247: return emitPropertyAssignment(node); - case 246: + case 248: return emitShorthandPropertyAssignment(node); case 136: return emitComputedPropertyName(node); - case 166: - return emitPropertyAccess(node); - case 167: - return emitIndexedAccess(node); case 168: - return emitCallExpression(node); + return emitPropertyAccess(node); case 169: - return emitNewExpression(node); + return emitIndexedAccess(node); case 170: - return emitTaggedTemplateExpression(node); + return emitCallExpression(node); case 171: - return emit(node.expression); - case 189: - return emit(node.expression); + return emitNewExpression(node); case 172: - return emitParenExpression(node); - case 213: + return emitTaggedTemplateExpression(node); case 173: + return emit(node.expression); + case 191: + return emit(node.expression); case 174: - return emitFunctionDeclaration(node); - case 175: - return emitDeleteExpression(node); - case 176: - return emitTypeOfExpression(node); - case 177: - return emitVoidExpression(node); - case 178: - return emitAwaitExpression(node); - case 179: - return emitPrefixUnaryExpression(node); - case 180: - return emitPostfixUnaryExpression(node); - case 181: - return emitBinaryExpression(node); - case 182: - return emitConditionalExpression(node); - case 185: - return emitSpreadElementExpression(node); - case 184: - return emitYieldExpression(node); - case 187: - return; - case 192: - case 219: - return emitBlock(node); - case 193: - return emitVariableStatement(node); - case 194: - return write(";"); - case 195: - return emitExpressionStatement(node); - case 196: - return emitIfStatement(node); - case 197: - return emitDoStatement(node); - case 198: - return emitWhileStatement(node); - case 199: - return emitForStatement(node); - case 201: - case 200: - return emitForInOrForOfStatement(node); - case 202: - case 203: - return emitBreakOrContinueStatement(node); - case 204: - return emitReturnStatement(node); - case 205: - return emitWithStatement(node); - case 206: - return emitSwitchStatement(node); - case 241: - case 242: - return emitCaseOrDefaultClause(node); - case 207: - return emitLabeledStatement(node); - case 208: - return emitThrowStatement(node); - case 209: - return emitTryStatement(node); - case 244: - return emitCatchClause(node); - case 210: - return emitDebuggerStatement(node); - case 211: - return emitVariableDeclaration(node); - case 186: - return emitClassExpression(node); - case 214: - return emitClassDeclaration(node); + return emitParenExpression(node); case 215: - return emitInterfaceDeclaration(node); - case 217: - return emitEnumDeclaration(node); - case 247: - return emitEnumMember(node); - case 218: - return emitModuleDeclaration(node); - case 222: - return emitImportDeclaration(node); + case 175: + case 176: + return emitFunctionDeclaration(node); + case 177: + return emitDeleteExpression(node); + case 178: + return emitTypeOfExpression(node); + case 179: + return emitVoidExpression(node); + case 180: + return emitAwaitExpression(node); + case 181: + return emitPrefixUnaryExpression(node); + case 182: + return emitPostfixUnaryExpression(node); + case 183: + return emitBinaryExpression(node); + case 184: + return emitConditionalExpression(node); + case 187: + return emitSpreadElementExpression(node); + case 186: + return emitYieldExpression(node); + case 189: + return; + case 194: case 221: + return emitBlock(node); + case 195: + return emitVariableStatement(node); + case 196: + return write(";"); + case 197: + return emitExpressionStatement(node); + case 198: + return emitIfStatement(node); + case 199: + return emitDoStatement(node); + case 200: + return emitWhileStatement(node); + case 201: + return emitForStatement(node); + case 203: + case 202: + return emitForInOrForOfStatement(node); + case 204: + case 205: + return emitBreakOrContinueStatement(node); + case 206: + return emitReturnStatement(node); + case 207: + return emitWithStatement(node); + case 208: + return emitSwitchStatement(node); + case 243: + case 244: + return emitCaseOrDefaultClause(node); + case 209: + return emitLabeledStatement(node); + case 210: + return emitThrowStatement(node); + case 211: + return emitTryStatement(node); + case 246: + return emitCatchClause(node); + case 212: + return emitDebuggerStatement(node); + case 213: + return emitVariableDeclaration(node); + case 188: + return emitClassExpression(node); + case 216: + return emitClassDeclaration(node); + case 217: + return emitInterfaceDeclaration(node); + case 219: + return emitEnumDeclaration(node); + case 249: + return emitEnumMember(node); + case 220: + return emitModuleDeclaration(node); + case 224: + return emitImportDeclaration(node); + case 223: return emitImportEqualsDeclaration(node); - case 228: + case 230: return emitExportDeclaration(node); - case 227: + case 229: return emitExportAssignment(node); - case 248: + case 250: return emitSourceFileNode(node); } } @@ -31411,7 +31931,7 @@ var ts; } function getLeadingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 248 || node.pos !== node.parent.pos) { + if (node.parent.kind === 250 || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { return getLeadingCommentsWithoutDetachedComments(); } @@ -31423,7 +31943,7 @@ var ts; } function getTrailingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 248 || node.end !== node.parent.end) { + if (node.parent.kind === 250 || node.end !== node.parent.end) { return ts.getTrailingCommentRanges(currentText, node.end); } } @@ -31489,18 +32009,30 @@ var ts; } } } + function writeComment(text, lineMap, writer, comment, newLine) { + emitPos(comment.pos); + ts.writeCommentRange(text, lineMap, writer, comment, newLine); + emitPos(comment.end); + } function emitShebang() { var shebang = ts.getShebang(currentText); if (shebang) { write(shebang); + writeLine(); } } var _a, _b; } - function emitFile(jsFilePath, sourceFile) { - emitJavaScript(jsFilePath, sourceFile); - if (compilerOptions.declaration) { - ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics); + function emitFile(_a, sourceFiles, isBundledEmit) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; + } + if (declarationFilePath) { + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } } } @@ -31514,10 +32046,10 @@ var ts; ts.ioWriteTime = 0; var emptyArray = []; ts.version = "1.8.0"; - function findConfigFile(searchPath) { + function findConfigFile(searchPath, fileExists) { var fileName = "tsconfig.json"; while (true) { - if (ts.sys.fileExists(fileName)) { + if (fileExists(fileName)) { return fileName; } var parentPath = ts.getDirectoryPath(searchPath); @@ -31541,21 +32073,22 @@ var ts; ? compilerOptions.moduleResolution : compilerOptions.module === 1 ? 2 : 1; switch (moduleResolution) { - case 2: return nodeModuleNameResolver(moduleName, containingFile, host); + case 2: return nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); case 1: return classicNameResolver(moduleName, containingFile, compilerOptions, host); } } ts.resolveModuleName = resolveModuleName; - function nodeModuleNameResolver(moduleName, containingFile, host) { + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { var failedLookupLocations = []; var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolvedFileName = loadNodeModuleFromFile(ts.supportedJsExtensions, candidate, failedLookupLocations, host); + var resolvedFileName = loadNodeModuleFromFile(supportedExtensions, candidate, failedLookupLocations, false, host); if (resolvedFileName) { return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }; } - resolvedFileName = loadNodeModuleFromDirectory(ts.supportedJsExtensions, candidate, failedLookupLocations, host); + resolvedFileName = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, false, host); return resolvedFileName ? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations } : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; @@ -31565,11 +32098,15 @@ var ts; } } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, host) { + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, onlyRecordFailures, host) { return ts.forEach(extensions, tryLoad); function tryLoad(ext) { var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (host.fileExists(fileName)) { + if (!onlyRecordFailures && host.fileExists(fileName)) { return fileName; } else { @@ -31578,9 +32115,10 @@ var ts; } } } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, host) { + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, host) { var packageJsonPath = ts.combinePaths(candidate, "package.json"); - if (host.fileExists(packageJsonPath)) { + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, host); + if (directoryExists && host.fileExists(packageJsonPath)) { var jsonContent; try { var jsonText = host.readFile(packageJsonPath); @@ -31589,8 +32127,9 @@ var ts; catch (e) { jsonContent = { typings: undefined }; } - if (jsonContent.typings) { - var result = loadNodeModuleFromFile(extensions, ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host); + if (typeof jsonContent.typings === "string") { + var path = ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)); + var result = loadNodeModuleFromFile(extensions, path, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(path), host), host); if (result) { return result; } @@ -31599,7 +32138,7 @@ var ts; else { failedLookupLocation.push(packageJsonPath); } - return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, host); + return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, !directoryExists, host); } function loadModuleFromNodeModules(moduleName, directory, host) { var failedLookupLocations = []; @@ -31608,12 +32147,13 @@ var ts; var baseName = ts.getBaseFileName(directory); if (baseName !== "node_modules") { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, host); var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var result = loadNodeModuleFromFile(ts.supportedExtensions, candidate, failedLookupLocations, host); + var result = loadNodeModuleFromFile(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; } - result = loadNodeModuleFromDirectory(ts.supportedExtensions, candidate, failedLookupLocations, host); + result = loadNodeModuleFromDirectory(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; } @@ -31638,10 +32178,10 @@ var ts; var searchName; var failedLookupLocations = []; var referencedSourceFile; - var extensions = compilerOptions.allowNonTsExtensions ? ts.supportedJsExtensions : ts.supportedExtensions; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); while (true) { searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - referencedSourceFile = ts.forEach(extensions, function (extension) { + referencedSourceFile = ts.forEach(supportedExtensions, function (extension) { if (extension === ".tsx" && !compilerOptions.jsx) { return undefined; } @@ -31736,14 +32276,15 @@ var ts; getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); } + readFile: function (fileName) { return ts.sys.readFile(fileName); }, + directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); } }; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -31781,8 +32322,10 @@ var ts; var noDiagnosticsTypeChecker; var classifiableNames; var skipDefaultLib = options.noLib; + var supportedExtensions = ts.getSupportedExtensions(options); var start = new Date().getTime(); host = host || createCompilerHost(options); + var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var currentDirectory = host.getCurrentDirectory(); var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) @@ -31795,7 +32338,8 @@ var ts; (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx)) { + (oldOptions.jsx !== options.jsx) || + (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } @@ -31805,9 +32349,7 @@ var ts; processRootFile(host.getDefaultLibFileName(options), true); } } - verifyCompilerOptions(); oldProgram = undefined; - ts.programTime += new Date().getTime() - start; program = { getRootFileNames: function () { return rootNames; }, getSourceFile: getSourceFile, @@ -31821,7 +32363,7 @@ var ts; getTypeChecker: getTypeChecker, getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, - getCommonSourceDirectory: function () { return commonSourceDirectory; }, + getCommonSourceDirectory: getCommonSourceDirectory, emit: emit, getCurrentDirectory: function () { return currentDirectory; }, getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, @@ -31830,7 +32372,23 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; } }; + verifyCompilerOptions(); + ts.programTime += new Date().getTime() - start; return program; + function getCommonSourceDirectory() { + if (typeof commonSourceDirectory === "undefined") { + if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(files); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); @@ -31876,7 +32434,7 @@ var ts; if (resolveModuleNamesWorker) { var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); - for (var i = 0; i < moduleNames.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var newResolution = resolutions[i]; var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); var resolutionChanged = oldResolution @@ -31897,7 +32455,7 @@ var ts; } newSourceFiles.push(newSourceFile); } - for (var i = 0, len = newSourceFiles.length; i < len; ++i) { + for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; @@ -31918,7 +32476,8 @@ var ts; getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFiles: program.getSourceFiles, - writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }) + writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }), + isEmitBlocked: isEmitBlocked }; } function getDiagnosticsProducingTypeChecker() { @@ -31931,9 +32490,15 @@ var ts; var _this = this; return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { - if (options.noEmitOnError && getPreEmitDiagnostics(program, undefined, cancellationToken).length > 0) { - return { diagnostics: [], sourceMaps: undefined, emitSkipped: true }; + if (options.noEmitOnError) { + var preEmitDiagnostics = getPreEmitDiagnostics(program, undefined, cancellationToken); + if (preEmitDiagnostics.length > 0) { + return { diagnostics: preEmitDiagnostics, sourceMaps: undefined, emitSkipped: true }; + } } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); var start = new Date().getTime(); @@ -31986,12 +32551,160 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? + getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : + typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); } + function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var diagnostics = []; + walk(sourceFile); + return diagnostics; + function walk(node) { + if (!node) { + return false; + } + switch (node.kind) { + case 223: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return true; + case 229: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return true; + case 216: + var classDeclaration = node; + if (checkModifiers(classDeclaration.modifiers) || + checkTypeParameters(classDeclaration.typeParameters)) { + return true; + } + break; + case 245: + var heritageClause = node; + if (heritageClause.token === 106) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 217: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 220: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 218: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return true; + case 143: + case 142: + case 144: + case 145: + case 146: + case 175: + case 215: + case 176: + case 215: + var functionDeclaration = node; + if (checkModifiers(functionDeclaration.modifiers) || + checkTypeParameters(functionDeclaration.typeParameters) || + checkTypeAnnotation(functionDeclaration.type)) { + return true; + } + break; + case 195: + var variableStatement = node; + if (checkModifiers(variableStatement.modifiers)) { + return true; + } + break; + case 213: + var variableDeclaration = node; + if (checkTypeAnnotation(variableDeclaration.type)) { + return true; + } + break; + case 170: + case 171: + 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)); + return true; + } + break; + case 138: + 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)); + return true; + } + if (parameter.questionToken) { + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return true; + } + if (parameter.type) { + diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 141: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 219: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 173: + var typeAssertionExpression = node; + diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return true; + case 139: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); + return true; + } + return ts.forEachChild(node, walk); + } + 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)); + return true; + } + return false; + } + function checkTypeAnnotation(type) { + if (type) { + diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkModifiers(modifiers) { + if (modifiers) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 112: + case 110: + case 111: + case 122: + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + case 113: + case 82: + case 74: + case 77: + case 115: + } + } + } + return false; + } + }); + } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { return runWithCancellationToken(function () { if (!ts.isDeclarationFile(sourceFile)) { @@ -32039,9 +32752,9 @@ var ts; function collect(node, allowRelativeModuleNames, collectOnlyRequireCalls) { if (!collectOnlyRequireCalls) { switch (node.kind) { - case 222: - case 221: - case 228: + case 224: + case 223: + case 230: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9) { break; @@ -32053,7 +32766,7 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 218: + case 220: if (node.name.kind === 9 && (node.flags & 4 || ts.isDeclarationFile(file))) { ts.forEachChild(node.body, function (node) { collect(node, false, collectOnlyRequireCalls); @@ -32076,9 +32789,9 @@ var ts; var diagnosticArgument; var diagnostic; if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; + diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; @@ -32096,7 +32809,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -32120,10 +32833,10 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function findSourceFile(fileName, normalizedAbsolutePath, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(normalizedAbsolutePath)) { - var file_1 = filesByName.get(normalizedAbsolutePath); - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== normalizedAbsolutePath) { + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + if (filesByName.contains(path)) { + var file_1 = filesByName.get(path); + if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } return file_1; @@ -32136,16 +32849,16 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); - filesByName.set(normalizedAbsolutePath, file); + filesByName.set(path, file); if (file) { - file.path = normalizedAbsolutePath; + file.path = path; if (host.useCaseSensitiveFileNames()) { - var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); + var existingFile = filesByNameIgnoreCase.get(path); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(normalizedAbsolutePath, file); + filesByNameIgnoreCase.set(path, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -32178,15 +32891,15 @@ var ts; file.resolvedModules = {}; var moduleNames = ts.map(file.imports, function (name) { return name.text; }); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); - for (var i = 0; i < file.imports.length; ++i) { + for (var i = 0; i < file.imports.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); if (resolution && !options.noResolve) { var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { if (!ts.isExternalModule(importedFile)) { - var start_2 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_2, file.imports[i].end - start_2, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); + var start_5 = ts.getTokenPosOfNode(file.imports[i], file); + fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { var firstRef = importedFile.referencedFiles[0]; @@ -32203,7 +32916,7 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var commonPathComponents; - ts.forEach(files, function (sourceFile) { + var failed = ts.forEach(files, function (sourceFile) { if (ts.isDeclarationFile(sourceFile)) { return; } @@ -32214,10 +32927,9 @@ var ts; return; } for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; + return true; } commonPathComponents.length = i; break; @@ -32227,6 +32939,9 @@ var ts; commonPathComponents.length = sourcePathComponents.length; } }); + if (failed) { + return ""; + } if (!commonPathComponents) { return currentDirectory; } @@ -32236,8 +32951,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -32271,14 +32986,14 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); } - if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap")); - } } if (options.inlineSources) { if (!options.sourceMap && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); } + if (options.sourceRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); + } } if (options.out && options.outFile) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); @@ -32287,10 +33002,9 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } - if (options.sourceRoot) { + if (options.sourceRoot && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); } - return; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; @@ -32307,7 +33021,7 @@ var ts; } else if (firstExternalModuleSourceFile && languageVersion < 2 && !options.module) { var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } if (options.module === 5 && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); @@ -32318,14 +33032,9 @@ var ts; if (options.outDir || options.sourceRoot || options.mapRoot) { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { - commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); - } - else { - commonSourceDirectory = computeCommonSourceDirectory(files); - } - if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { - commonSourceDirectory += ts.directorySeparator; + var dir = getCommonSourceDirectory(); + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { @@ -32342,10 +33051,42 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } + else if (options.allowJs && options.declaration) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } + if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + } + if (!options.noEmit) { + var emitHost = getEmitHost(); + var emitFilesSeen = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen); + }); + } + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); + if (filesByName.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + } + if (emitFilesSeen.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + } + else { + emitFilesSeen.set(emitFilePath, true); + } + } + } + } + function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); } } ts.createProgram = createProgram; @@ -32360,7 +33101,7 @@ var ts; } var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) { + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) { return undefined; @@ -32371,14 +33112,20 @@ var ts; } return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - return ts.createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd()); + var start = startNode.decorators ? + ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + startNode.getStart(sourceFile); + return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { - if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { return spanInNode(node); } return spanInNode(otherwiseOnNode); } + function spanInNodeArray(nodeArray) { + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } @@ -32388,98 +33135,103 @@ var ts; function spanInNode(node) { if (node) { if (ts.isExpression(node)) { - if (node.parent.kind === 197) { + if (node.parent.kind === 199) { return spanInPreviousNode(node); } - if (node.parent.kind === 199) { + if (node.parent.kind === 139) { + return spanInNode(node.parent); + } + if (node.parent.kind === 201) { return textSpan(node); } - if (node.parent.kind === 181 && node.parent.operatorToken.kind === 24) { + if (node.parent.kind === 183 && node.parent.operatorToken.kind === 24) { return textSpan(node); } - if (node.parent.kind === 174 && node.parent.body === node) { + if (node.parent.kind === 176 && node.parent.body === node) { return textSpan(node); } } switch (node.kind) { - case 193: + case 195: return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 211: + case 213: case 141: case 140: return spanInVariableDeclaration(node); case 138: return spanInParameterDeclaration(node); - case 213: + case 215: case 143: case 142: case 145: case 146: case 144: - case 173: - case 174: + case 175: + case 176: return spanInFunctionDeclaration(node); - case 192: + case 194: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } - case 219: + case 221: return spanInBlock(node); - case 244: + case 246: return spanInBlock(node.block); - case 195: + case 197: return textSpan(node.expression); - case 204: + case 206: return textSpan(node.getChildAt(0), node.expression); + case 200: + return textSpan(node, ts.findNextToken(node.expression, node)); + case 199: + return spanInNode(node.statement); + case 212: + return textSpan(node.getChildAt(0)); case 198: return textSpan(node, ts.findNextToken(node.expression, node)); - case 197: - return spanInNode(node.statement); - case 210: - return textSpan(node.getChildAt(0)); - case 196: - return textSpan(node, ts.findNextToken(node.expression, node)); - case 207: - return spanInNode(node.statement); - case 203: - case 202: - return textSpan(node.getChildAt(0), node.label); - case 199: - return spanInForStatement(node); - case 200: - case 201: - return textSpan(node, ts.findNextToken(node.expression, node)); - case 206: - return textSpan(node, ts.findNextToken(node.expression, node)); - case 241: - case 242: - return spanInNode(node.statements[0]); case 209: - return spanInBlock(node.tryBlock); + return spanInNode(node.statement); + case 205: + case 204: + return textSpan(node.getChildAt(0), node.label); + case 201: + return spanInForStatement(node); + case 202: + case 203: + return textSpan(node, ts.findNextToken(node.expression, node)); case 208: + return textSpan(node, ts.findNextToken(node.expression, node)); + case 243: + case 244: + return spanInNode(node.statements[0]); + case 211: + return spanInBlock(node.tryBlock); + case 210: return textSpan(node, node.expression); - case 227: + case 229: return textSpan(node, node.expression); - case 221: + case 223: return textSpan(node, node.moduleReference); - case 222: + case 224: return textSpan(node, node.moduleSpecifier); - case 228: + case 230: return textSpan(node, node.moduleSpecifier); - case 218: + case 220: if (ts.getModuleInstanceState(node) !== 1) { return undefined; } - case 214: - case 217: - case 247: - case 168: - case 169: - return textSpan(node); - case 205: - return spanInNode(node.statement); - case 215: case 216: + case 219: + case 249: + case 170: + case 171: + return textSpan(node); + case 207: + return spanInNode(node.statement); + case 139: + return spanInNodeArray(node.parent.decorators); + case 217: + case 218: return undefined; case 23: case 1: @@ -32506,10 +33258,10 @@ var ts; case 85: return spanInNextNode(node); default: - if (node.parent.kind === 245 && node.parent.name === node) { + if (node.parent.kind === 247 && node.parent.name === node) { return spanInNode(node.parent.initializer); } - if (node.parent.kind === 171 && node.parent.type === node) { + if (node.parent.kind === 173 && node.parent.type === node) { return spanInNode(node.parent.expression); } if (ts.isFunctionLike(node.parent) && node.parent.type === node) { @@ -32519,12 +33271,12 @@ var ts; } } function spanInVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.parent.kind === 200 || - variableDeclaration.parent.parent.kind === 201) { + if (variableDeclaration.parent.parent.kind === 202 || + variableDeclaration.parent.parent.kind === 203) { return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.parent.kind === 193; - var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 199 && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); + var isParentVariableStatement = variableDeclaration.parent.parent.kind === 195; + var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 201 && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); var declarations = isParentVariableStatement ? variableDeclaration.parent.parent.declarationList.declarations : isDeclarationOfForStatement @@ -32570,7 +33322,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return !!(functionDeclaration.flags & 2) || - (functionDeclaration.parent.kind === 214 && functionDeclaration.kind !== 144); + (functionDeclaration.parent.kind === 216 && functionDeclaration.kind !== 144); } function spanInFunctionDeclaration(functionDeclaration) { if (!functionDeclaration.body) { @@ -32590,23 +33342,23 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 218: + case 220: if (ts.getModuleInstanceState(block.parent) !== 1) { return undefined; } - case 198: - case 196: case 200: - case 201: + case 198: + case 202: + case 203: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); - case 199: + case 201: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } return spanInNode(block.statements[0]); } function spanInForStatement(forStatement) { if (forStatement.initializer) { - if (forStatement.initializer.kind === 212) { + if (forStatement.initializer.kind === 214) { var variableDeclarationList = forStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); @@ -32625,33 +33377,33 @@ var ts; } function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 217: + case 219: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 214: + case 216: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 220: + case 222: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } return spanInNode(node.parent); } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 219: + case 221: if (ts.getModuleInstanceState(node.parent.parent) !== 1) { return undefined; } - case 217: - case 214: + case 219: + case 216: return textSpan(node); - case 192: + case 194: if (ts.isFunctionBlock(node.parent)) { return textSpan(node); } - case 244: + case 246: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 220: + case 222: var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); if (lastClause) { @@ -32663,43 +33415,43 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 197) { + if (node.parent.kind === 199) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInCloseParenToken(node) { switch (node.parent.kind) { - case 173: - case 213: - case 174: + case 175: + case 215: + case 176: case 143: case 142: case 145: case 146: case 144: - case 198: - case 197: + case 200: case 199: + case 201: return spanInPreviousNode(node); default: return spanInNode(node.parent); } } function spanInColonToken(node) { - if (ts.isFunctionLike(node.parent) || node.parent.kind === 245) { + if (ts.isFunctionLike(node.parent) || node.parent.kind === 247) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 171) { + if (node.parent.kind === 173) { return spanInNode(node.parent.expression); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 197) { + if (node.parent.kind === 199) { return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); } return spanInNode(node.parent); @@ -32777,7 +33529,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 174; + return ts.isFunctionBlock(node) && node.parent.kind !== 176; } var depth = 0; var maxDepth = 20; @@ -32789,23 +33541,23 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 192: + case 194: if (!ts.isFunctionBlock(n)) { var parent_7 = n.parent; var openBrace = ts.findChildOfKind(n, 15, sourceFile); var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - if (parent_7.kind === 197 || - parent_7.kind === 200 || + if (parent_7.kind === 199 || + parent_7.kind === 202 || + parent_7.kind === 203 || parent_7.kind === 201 || - parent_7.kind === 199 || - parent_7.kind === 196 || parent_7.kind === 198 || - parent_7.kind === 205 || - parent_7.kind === 244) { + parent_7.kind === 200 || + parent_7.kind === 207 || + parent_7.kind === 246) { addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_7.kind === 209) { + if (parent_7.kind === 211) { var tryStatement = parent_7; if (tryStatement.tryBlock === n) { addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); @@ -32828,23 +33580,23 @@ var ts; }); break; } - case 219: { + case 221: { var openBrace = ts.findChildOfKind(n, 15, sourceFile); var closeBrace = ts.findChildOfKind(n, 16, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 214: - case 215: + case 216: case 217: - case 165: - case 220: { + case 219: + case 167: + case 222: { var openBrace = ts.findChildOfKind(n, 15, sourceFile); var closeBrace = ts.findChildOfKind(n, 16, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 164: + case 166: var openBracket = ts.findChildOfKind(n, 19, sourceFile); var closeBracket = ts.findChildOfKind(n, 20, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); @@ -32871,10 +33623,10 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_32 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_32); + for (var name_28 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_28); if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_32); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_28); if (!matches) { continue; } @@ -32885,14 +33637,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_32); + matches = patternMatcher.getMatches(containers, name_28); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_32, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_28, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -32946,7 +33698,7 @@ var ts; } return true; } - if (expression.kind === 166) { + if (expression.kind === 168) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -33011,7 +33763,7 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile) { + function getNavigationBarItems(sourceFile, compilerOptions) { var hasGlobalNode = false; return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); function getIndent(node) { @@ -33019,14 +33771,14 @@ var ts; var current = node.parent; while (current) { switch (current.kind) { - case 218: + case 220: do { current = current.parent; - } while (current.kind === 218); - case 214: + } while (current.kind === 220); + case 216: + case 219: case 217: case 215: - case 213: indent++; } current = current.parent; @@ -33037,26 +33789,26 @@ var ts; var childNodes = []; function visit(node) { switch (node.kind) { - case 193: + case 195: ts.forEach(node.declarationList.declarations, visit); break; - case 161: - case 162: + case 163: + case 164: ts.forEach(node.elements, visit); break; - case 228: + case 230: if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 222: + case 224: var importClause = node.importClause; if (importClause) { if (importClause.name) { childNodes.push(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224) { + if (importClause.namedBindings.kind === 226) { childNodes.push(importClause.namedBindings); } else { @@ -33065,20 +33817,20 @@ var ts; } } break; - case 163: - case 211: + case 165: + case 213: if (ts.isBindingPattern(node.name)) { visit(node.name); break; } - case 214: + case 216: + case 219: case 217: + case 220: case 215: - case 218: - case 213: - case 221: - case 226: - case 230: + case 223: + case 228: + case 232: childNodes.push(node); break; } @@ -33113,17 +33865,17 @@ var ts; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { var node = nodes_4[_i]; switch (node.kind) { - case 214: + case 216: + case 219: case 217: - case 215: topLevelNodes.push(node); break; - case 218: + case 220: var moduleDeclaration = node; topLevelNodes.push(node); addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); break; - case 213: + case 215: var functionDeclaration = node; if (isTopLevelFunctionDeclaration(functionDeclaration)) { topLevelNodes.push(node); @@ -33134,9 +33886,9 @@ var ts; } } function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 213) { - if (functionDeclaration.body && functionDeclaration.body.kind === 192) { - if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 213 && !isEmpty(s.name.text); })) { + if (functionDeclaration.kind === 215) { + if (functionDeclaration.body && functionDeclaration.body.kind === 194) { + if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 215 && !isEmpty(s.name.text); })) { return true; } if (!ts.isFunctionBlock(functionDeclaration.parent)) { @@ -33206,7 +33958,7 @@ var ts; return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); case 149: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 247: + case 249: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); case 147: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); @@ -33215,16 +33967,16 @@ var ts; case 141: case 140: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 213: + case 215: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 211: - case 163: + case 213: + case 165: var variableDeclarationNode; - var name_33; - if (node.kind === 163) { - name_33 = node.name; + var name_29; + if (node.kind === 165) { + name_29 = node.name; variableDeclarationNode = node; - while (variableDeclarationNode && variableDeclarationNode.kind !== 211) { + while (variableDeclarationNode && variableDeclarationNode.kind !== 213) { variableDeclarationNode = variableDeclarationNode.parent; } ts.Debug.assert(variableDeclarationNode !== undefined); @@ -33232,24 +33984,24 @@ var ts; else { ts.Debug.assert(!ts.isBindingPattern(node.name)); variableDeclarationNode = node; - name_33 = node.name; + name_29 = node.name; } if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.constElement); + return createItem(node, getTextOfNode(name_29), ts.ScriptElementKind.constElement); } else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.letElement); + return createItem(node, getTextOfNode(name_29), ts.ScriptElementKind.letElement); } else { - return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.variableElement); + return createItem(node, getTextOfNode(name_29), ts.ScriptElementKind.variableElement); } case 144: return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 230: - case 226: - case 221: + case 232: + case 228: case 223: - case 224: + case 225: + case 226: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); } return undefined; @@ -33279,17 +34031,17 @@ var ts; } function createTopLevelItem(node) { switch (node.kind) { - case 248: + case 250: return createSourceFileItem(node); - case 214: + case 216: return createClassItem(node); - case 217: + case 219: return createEnumItem(node); - case 215: + case 217: return createIterfaceItem(node); - case 218: + case 220: return createModuleItem(node); - case 213: + case 215: return createFunctionItem(node); } return undefined; @@ -33299,7 +34051,7 @@ var ts; } var result = []; result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 218) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 220) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -33311,7 +34063,7 @@ var ts; return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } function createFunctionItem(node) { - if (node.body && node.body.kind === 192) { + if (node.body && node.body.kind === 194) { var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } @@ -33359,13 +34111,13 @@ var ts; return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); } function getInnermostModule(node) { - while (node.body.kind === 218) { + while (node.body.kind === 220) { node = node.body; } return node; } function getNodeSpan(node) { - return node.kind === 248 + return node.kind === 250 ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); } @@ -33396,7 +34148,6 @@ var ts; function createPatternMatcher(pattern) { var stringToWordSpans = {}; pattern = pattern.trim(); - var fullPatternSegment = createSegment(pattern); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); return { @@ -33426,7 +34177,7 @@ var ts; return undefined; } var totalMatch = candidateMatch; - for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i--, j--) { + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { var segment = dotSeparatedSegments[i]; var containerName = candidateContainers[j]; var containerMatch = matchSegment(containerName, segment); @@ -33593,33 +34344,6 @@ var ts; } } ts.createPatternMatcher = createPatternMatcher; - function patternMatchCompareTo(match1, match2) { - return compareType(match1, match2) || - compareCamelCase(match1, match2) || - compareCase(match1, match2) || - comparePunctuation(match1, match2); - } - function comparePunctuation(result1, result2) { - if (result1.punctuationStripped !== result2.punctuationStripped) { - return result1.punctuationStripped ? 1 : -1; - } - return 0; - } - function compareCase(result1, result2) { - if (result1.isCaseSensitive !== result2.isCaseSensitive) { - return result1.isCaseSensitive ? -1 : 1; - } - return 0; - } - function compareType(result1, result2) { - return result1.kind - result2.kind; - } - function compareCamelCase(result1, result2) { - if (result1.kind === PatternMatchKind.camelCase && result2.kind === PatternMatchKind.camelCase) { - return result2.camelCaseWeight - result1.camelCaseWeight; - } - return 0; - } function createSegment(text) { return { totalTextChunk: createTextChunk(text), @@ -33649,14 +34373,6 @@ var ts; var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function containsUpperCaseLetter(string) { - for (var i = 0, n = string.length; i < n; i++) { - if (isUpperCaseLetter(string.charCodeAt(i))) { - return true; - } - } - return false; - } function startsWith(string, search) { for (var i = 0, n = search.length; i < n; i++) { if (string.charCodeAt(i) !== search.charCodeAt(i)) { @@ -33705,9 +34421,10 @@ var ts; for (var i = 0; i < pattern.length; i++) { var ch = pattern.charCodeAt(i); if (isWordChar(ch)) { - if (wordLength++ === 0) { + if (wordLength === 0) { wordStart = i; } + wordLength++; } else { if (wordLength > 0) { @@ -33855,14 +34572,14 @@ var ts; } return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo); function createJavaScriptSignatureHelpItems(argumentInfo) { - if (argumentInfo.invocation.kind !== 168) { + if (argumentInfo.invocation.kind !== 170) { return undefined; } var callExpression = argumentInfo.invocation; var expression = callExpression.expression; var name = expression.kind === 69 ? expression - : expression.kind === 166 + : expression.kind === 168 ? expression.name : undefined; if (!name || !name.text) { @@ -33891,7 +34608,7 @@ var ts; } } function getImmediatelyContainingArgumentInfo(node) { - if (node.parent.kind === 168 || node.parent.kind === 169) { + if (node.parent.kind === 170 || node.parent.kind === 171) { var callExpression = node.parent; if (node.kind === 25 || node.kind === 17) { @@ -33922,23 +34639,23 @@ var ts; }; } } - else if (node.kind === 11 && node.parent.kind === 170) { + else if (node.kind === 11 && node.parent.kind === 172) { if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, 0); } } - else if (node.kind === 12 && node.parent.parent.kind === 170) { + else if (node.kind === 12 && node.parent.parent.kind === 172) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183); + ts.Debug.assert(templateExpression.kind === 185); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } - else if (node.parent.kind === 190 && node.parent.parent.parent.kind === 170) { + else if (node.parent.kind === 192 && node.parent.parent.parent.kind === 172) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183); + ts.Debug.assert(templateExpression.kind === 185); if (node.kind === 14 && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } @@ -34002,7 +34719,7 @@ var ts; var template = taggedTemplate.template; var applicableSpanStart = template.getStart(); var applicableSpanEnd = template.getEnd(); - if (template.kind === 183) { + if (template.kind === 185) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, false); @@ -34011,7 +34728,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node) { - for (var n = node; n.kind !== 248; n = n.parent) { + for (var n = node; n.kind !== 250; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -34191,24 +34908,24 @@ var ts; return false; } switch (n.kind) { - case 214: - case 215: + case 216: case 217: - case 165: - case 161: - case 155: - case 192: case 219: - case 220: + case 167: + case 163: + case 155: + case 194: + case 221: + case 222: return nodeEndsWith(n, 16, sourceFile); - case 244: + case 246: return isCompletedNode(n.block, sourceFile); - case 169: + case 171: if (!n.arguments) { return true; } - case 168: - case 172: + case 170: + case 174: case 160: return nodeEndsWith(n, 18, sourceFile); case 152: @@ -34217,13 +34934,13 @@ var ts; case 144: case 145: case 146: - case 213: - case 173: + case 215: + case 175: case 143: case 142: case 148: case 147: - case 174: + case 176: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -34231,19 +34948,19 @@ var ts; return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 18, sourceFile); - case 218: + case 220: return n.body && isCompletedNode(n.body, sourceFile); - case 196: + case 198: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 195: + case 197: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 23); + case 166: case 164: - case 162: - case 167: + case 169: case 136: case 157: return nodeEndsWith(n, 20, sourceFile); @@ -34252,15 +34969,15 @@ var ts; return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 20, sourceFile); - case 241: - case 242: + case 243: + case 244: return false; - case 199: - case 200: case 201: - case 198: + case 202: + case 203: + case 200: return isCompletedNode(n.statement, sourceFile); - case 197: + case 199: var hasWhileKeyword = findChildOfKind(n, 104, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, 18, sourceFile); @@ -34268,25 +34985,25 @@ var ts; return isCompletedNode(n.statement, sourceFile); case 154: return isCompletedNode(n.exprName, sourceFile); - case 176: - case 175: + case 178: case 177: - case 184: - case 185: + case 179: + case 186: + case 187: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 170: + case 172: return isCompletedNode(n.template, sourceFile); - case 183: + case 185: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 190: + case 192: return ts.nodeIsPresent(n.literal); - case 179: - return isCompletedNode(n.operand, sourceFile); case 181: + return isCompletedNode(n.operand, sourceFile); + case 183: return isCompletedNode(n.right, sourceFile); - case 182: + case 184: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -34329,7 +35046,7 @@ var ts; ts.findChildOfKind = findChildOfKind; function findContainingList(node) { var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - if (c.kind === 271 && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 273 && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -34409,7 +35126,7 @@ var ts; function findPrecedingToken(position, sourceFile, startNode) { return find(startNode || sourceFile); function findRightmostToken(n) { - if (isToken(n) || n.kind === 236) { + if (isToken(n) || n.kind === 238) { return n; } var children = n.getChildren(); @@ -34417,16 +35134,16 @@ var ts; return candidate && findRightmostToken(candidate); } function find(n) { - if (isToken(n) || n.kind === 236) { + if (isToken(n) || n.kind === 238) { return n; } var children = n.getChildren(); for (var i = 0, len = children.length; i < len; i++) { var child = children[i]; - if (position < child.end && (nodeHasTokens(child) || child.kind === 236)) { + if (position < child.end && (nodeHasTokens(child) || child.kind === 238)) { var start = child.getStart(sourceFile); var lookInPreviousChild = (start >= position) || - (child.kind === 236 && start === child.end); + (child.kind === 238 && start === child.end); if (lookInPreviousChild) { var candidate = findRightmostChildNodeWithTokens(children, i); return candidate && findRightmostToken(candidate); @@ -34436,7 +35153,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 248); + ts.Debug.assert(startNode !== undefined || n.kind === 250); if (children.length) { var candidate = findRightmostChildNodeWithTokens(children, children.length); return candidate && findRightmostToken(candidate); @@ -34453,7 +35170,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); - return token && token.kind === 9 && position > token.getStart(); + return token && (token.kind === 9 || token.kind === 162) && position > token.getStart(); } ts.isInString = isInString; function isInComment(sourceFile, position) { @@ -34536,10 +35253,10 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 151 || node.kind === 168) { + if (node.kind === 151 || node.kind === 170) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 214 || node.kind === 215) { + if (ts.isFunctionLike(node) || node.kind === 216 || node.kind === 217) { return node.typeParameters; } return undefined; @@ -34562,6 +35279,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 + || kind === 162 || kind === 10 || ts.isTemplateLiteralKind(kind)) { return true; @@ -34789,7 +35507,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 226 || location.parent.kind === 230) && + (location.parent.kind === 228 || location.parent.kind === 232) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -34827,6 +35545,7 @@ var ts; advance: advance, readTokenInfo: readTokenInfo, isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, close: function () { ts.Debug.assert(scanner !== undefined); @@ -34890,10 +35609,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 238: - case 235: + case 240: case 237: - case 234: + case 239: + case 236: return node.kind === 69; } } @@ -35081,7 +35800,7 @@ var ts; return false; }; return FormattingContext; - })(); + }()); formatting.FormattingContext = FormattingContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -35102,7 +35821,7 @@ var ts; "flag=" + this.Flag + "]"; }; return Rule; - })(); + }()); formatting.Rule = Rule; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -35132,7 +35851,7 @@ var ts; return new RuleDescriptor(left, right); }; return RuleDescriptor; - })(); + }()); formatting.RuleDescriptor = RuleDescriptor; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -35159,7 +35878,7 @@ var ts; return result; }; return RuleOperation; - })(); + }()); formatting.RuleOperation = RuleOperation; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -35192,7 +35911,7 @@ var ts; }; RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; - })(); + }()); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -35259,6 +35978,7 @@ var ts; this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115, 73, 122, 77, 81, 82, 83, 123, 106, 89, 107, 125, 126, 110, 112, 111, 129, 113, 132]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([83, 106])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2)); + this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 34), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22, 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.FromTokens([18, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); @@ -35278,65 +35998,61 @@ var ts; this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([114, 37]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2)); this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsSameLineTokenContext), 2)); this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118, 87), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.SpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69, formatting.Shared.TokenRange.FromTokens([11, 12])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - 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.IsSameLineTokenContext), 8)); - this.HighPriorityCommonRules = - [ - this.IgnoreBeforeComment, this.IgnoreAfterLineComment, - this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, - this.NoSpaceAfterQuestionMark, - this.NoSpaceBeforeDot, this.NoSpaceAfterDot, - this.NoSpaceAfterUnaryPrefixOperator, - this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, - this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, - this.SpaceAfterPostincrementWhenFollowedByAdd, - this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, - this.SpaceAfterPostdecrementWhenFollowedBySubtract, - this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, - this.NoSpaceAfterCloseBrace, - this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, - this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, - this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, - this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, - this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, - this.NoSpaceBetweenReturnAndSemicolon, - this.SpaceAfterCertainKeywords, - this.SpaceAfterLetConstInVariableDeclaration, - this.NoSpaceBeforeOpenParenInFuncCall, - this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, - this.SpaceAfterVoidOperator, - this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, - this.SpaceBetweenTagAndTemplateString, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, - this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, - this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, - this.SpaceAfterModuleName, - this.SpaceAfterArrow, - this.NoSpaceAfterEllipsis, - this.NoSpaceAfterOptionalParameters, - this.NoSpaceBetweenEmptyInterfaceBraceBrackets, - this.NoSpaceBeforeOpenAngularBracket, - this.NoSpaceBetweenCloseParenAndAngularBracket, - this.NoSpaceAfterOpenAngularBracket, - this.NoSpaceBeforeCloseAngularBracket, - this.NoSpaceAfterCloseAngularBracket, - this.NoSpaceAfterTypeAssertion, - this.SpaceBeforeAt, - this.NoSpaceAfterAt, - this.SpaceAfterDecorator, - ]; - this.LowPriorityCommonRules = - [ - this.NoSpaceBeforeSemicolon, - this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, - this.NoSpaceBeforeComma, - this.NoSpaceBeforeOpenBracket, - this.NoSpaceAfterCloseBracket, - this.SpaceAfterSemicolon, - 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.IsSameLineTokenContext), 2)); + this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69, formatting.Shared.TokenRange.FromTokens([11, 12])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); + this.HighPriorityCommonRules = [ + this.IgnoreBeforeComment, this.IgnoreAfterLineComment, + this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, + this.NoSpaceAfterQuestionMark, + this.NoSpaceBeforeDot, this.NoSpaceAfterDot, + this.NoSpaceAfterUnaryPrefixOperator, + this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, + this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, + this.SpaceAfterPostincrementWhenFollowedByAdd, + this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, + this.SpaceAfterPostdecrementWhenFollowedBySubtract, + this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, + this.NoSpaceAfterCloseBrace, + this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, + this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, + this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, + this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, + this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, + this.NoSpaceBetweenReturnAndSemicolon, + this.SpaceAfterCertainKeywords, + this.SpaceAfterLetConstInVariableDeclaration, + this.NoSpaceBeforeOpenParenInFuncCall, + this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, + this.SpaceAfterVoidOperator, + this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, + this.NoSpaceBetweenTagAndTemplateString, + this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, + this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, + this.SpaceAfterModuleName, + this.SpaceBeforeArrow, this.SpaceAfterArrow, + this.NoSpaceAfterEllipsis, + this.NoSpaceAfterOptionalParameters, + this.NoSpaceBetweenEmptyInterfaceBraceBrackets, + this.NoSpaceBeforeOpenAngularBracket, + this.NoSpaceBetweenCloseParenAndAngularBracket, + this.NoSpaceAfterOpenAngularBracket, + this.NoSpaceBeforeCloseAngularBracket, + this.NoSpaceAfterCloseAngularBracket, + this.NoSpaceAfterTypeAssertion, + this.SpaceBeforeAt, + this.NoSpaceAfterAt, + this.SpaceAfterDecorator, + ]; + this.LowPriorityCommonRules = [ + this.NoSpaceBeforeSemicolon, + this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, + this.NoSpaceBeforeComma, + this.NoSpaceBeforeOpenBracket, + this.NoSpaceAfterCloseBracket, + this.SpaceAfterSemicolon, + 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.IsSameLineTokenContext, Rules.IsNextTokenNotCloseBracket), 2)); this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, 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.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2)); @@ -35359,45 +36075,49 @@ var ts; this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); + 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.IsSameLineTokenContext), 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.IsSameLineTokenContext), 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.IsSameLineTokenContext), 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)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_34 in o) { - if (o[name_34] === rule) { - return name_34; + for (var name_30 in o) { + if (o[name_30] === rule) { + return name_30; } } throw new Error("Unknown rule"); }; Rules.IsForContext = function (context) { - return context.contextNode.kind === 199; + return context.contextNode.kind === 201; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 181: - case 182: - case 189: + case 183: + case 184: + case 191: case 150: case 158: case 159: return true; - case 163: - case 216: - case 221: - case 211: + case 165: + case 218: + case 223: + case 213: case 138: - case 247: + case 249: case 141: case 140: return context.currentTokenSpan.kind === 56 || context.nextTokenSpan.kind === 56; - case 200: + case 202: return context.currentTokenSpan.kind === 90 || context.nextTokenSpan.kind === 90; - case 201: + case 203: return context.currentTokenSpan.kind === 134 || context.nextTokenSpan.kind === 134; } return false; @@ -35406,7 +36126,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 182; + return context.contextNode.kind === 184; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context); @@ -35431,86 +36151,86 @@ var ts; return true; } switch (node.kind) { - case 192: - case 220: - case 165: - case 219: + case 194: + case 222: + case 167: + case 221: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 213: + case 215: case 143: case 142: case 145: case 146: case 147: - case 173: + case 175: case 144: - case 174: - case 215: + case 176: + case 217: return true; } return false; }; Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 213 || context.contextNode.kind === 173; + return context.contextNode.kind === 215 || context.contextNode.kind === 175; }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 214: - case 186: - case 215: + case 216: + case 188: case 217: + case 219: case 155: - case 218: + case 220: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 214: - case 218: - case 217: - case 192: - case 244: + case 216: + case 220: case 219: - case 206: + case 194: + case 246: + case 221: + case 208: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 196: - case 206: - case 199: - case 200: - case 201: case 198: - case 209: - case 197: - case 205: - case 244: + case 208: + case 201: + case 202: + case 203: + case 200: + case 211: + case 199: + case 207: + case 246: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 165; + return context.contextNode.kind === 167; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 168; + return context.contextNode.kind === 170; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 169; + return context.contextNode.kind === 171; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); @@ -35518,8 +36238,11 @@ var ts; Rules.IsPreviousTokenNotComma = function (context) { return context.currentTokenSpan.kind !== 24; }; + Rules.IsNextTokenNotCloseBracket = function (context) { + return context.nextTokenSpan.kind !== 20; + }; Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 174; + return context.contextNode.kind === 176; }; Rules.IsSameLineTokenContext = function (context) { return context.TokensAreOnSameLine(); @@ -35540,14 +36263,14 @@ var ts; return node.kind === 139; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 212 && + return context.currentTokenParent.kind === 214 && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { return context.formattingRequestKind !== 2; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 218; + return context.contextNode.kind === 220; }; Rules.IsObjectTypeContext = function (context) { return context.contextNode.kind === 155; @@ -35558,20 +36281,20 @@ var ts; } switch (parent.kind) { case 151: - case 171: - case 214: - case 186: - case 215: - case 213: case 173: - case 174: + case 216: + case 188: + case 217: + case 215: + case 175: + case 176: case 143: case 142: case 147: case 148: - case 168: - case 169: - case 188: + case 170: + case 171: + case 190: return true; default: return false; @@ -35582,16 +36305,16 @@ var ts; Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 171; + return context.contextNode.kind === 173; }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 103 && context.currentTokenParent.kind === 177; + return context.currentTokenSpan.kind === 103 && context.currentTokenParent.kind === 179; }; Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 184 && context.contextNode.expression !== undefined; + return context.contextNode.kind === 186 && context.contextNode.expression !== undefined; }; return Rules; - })(); + }()); formatting.Rules = Rules; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -35655,7 +36378,7 @@ var ts; return null; }; return RulesMap; - })(); + }()); formatting.RulesMap = RulesMap; var MaskBitSize = 5; var Mask = 0x1f; @@ -35692,7 +36415,7 @@ var ts; this.rulesInsertionIndexBitmap = temp; }; return RulesBucketConstructionState; - })(); + }()); formatting.RulesBucketConstructionState = RulesBucketConstructionState; var RulesBucket = (function () { function RulesBucket() { @@ -35727,7 +36450,7 @@ var ts; state.IncreaseInsertionIndex(position); }; return RulesBucket; - })(); + }()); formatting.RulesBucket = RulesBucket; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -35753,7 +36476,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenRangeAccess; - })(); + }()); Shared.TokenRangeAccess = TokenRangeAccess; var TokenValuesAccess = (function () { function TokenValuesAccess(tks) { @@ -35766,7 +36489,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenValuesAccess; - })(); + }()); Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { @@ -35779,7 +36502,7 @@ var ts; return tokenValue === this.token; }; return TokenSingleValueAccess; - })(); + }()); Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { @@ -35798,7 +36521,7 @@ var ts; return "[allTokens]"; }; return TokenAllAccess; - })(); + }()); Shared.TokenAllAccess = TokenAllAccess; var TokenRange = (function () { function TokenRange(tokenAccess) { @@ -35840,7 +36563,7 @@ var ts; TokenRange.Comments = TokenRange.FromTokens([2, 3]); TokenRange.TypeNames = TokenRange.FromTokens([69, 128, 130, 120, 131, 103, 117]); return TokenRange; - })(); + }()); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -35911,6 +36634,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } + if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); + } + else { + rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); + } if (options.InsertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } @@ -35936,7 +36667,7 @@ var ts; return rules; }; return RulesProvider; - })(); + }()); formatting.RulesProvider = RulesProvider; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -36009,17 +36740,17 @@ var ts; } function isListElement(parent, node) { switch (parent.kind) { - case 214: - case 215: + case 216: + case 217: return ts.rangeContainsRange(parent.members, node); - case 218: + case 220: var body = parent.body; - return body && body.kind === 192 && ts.rangeContainsRange(body.statements, node); - case 248: - case 192: - case 219: + return body && body.kind === 194 && ts.rangeContainsRange(body.statements, node); + case 250: + case 194: + case 221: return ts.rangeContainsRange(parent.statements, node); - case 244: + case 246: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -36083,17 +36814,17 @@ var ts; } function getOwnOrInheritedDelta(n, options, sourceFile) { var previousLine = -1; - var childKind = 0; + var child; while (n) { var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; if (previousLine !== -1 && line !== previousLine) { break; } - if (formatting.SmartIndenter.shouldIndentChildNode(n.kind, childKind)) { + if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { return options.IndentSize; } previousLine = line; - childKind = n.kind; + child = n; n = n.parent; } return 0; @@ -36121,10 +36852,18 @@ var ts; var delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile); processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } + if (!formattingScanner.isOnToken()) { + var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (leadingTrivia) { + processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined); + trimTrailingWhitespacesForRemainingRange(); + } + } formattingScanner.close(); return edits; function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { - if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos)) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || + ts.rangeContainsStartEnd(range, startPos, endPos)) { if (inheritedIndentation !== -1) { return inheritedIndentation; } @@ -36141,33 +36880,20 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - if (indentation === -1) { - if (isSomeBlock(node.kind)) { - if (isSomeBlock(parent.kind) || - parent.kind === 248 || - parent.kind === 241 || - parent.kind === 242) { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - else { - indentation = parentDynamicIndentation.getIndentation(); - } - } - else { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); - } - else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - } - } - var delta = formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + } + else if (indentation === -1) { + if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + indentation = parentDynamicIndentation.getIndentation(); + } + else { + indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + } } return { indentation: indentation, @@ -36179,10 +36905,10 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 214: return 73; - case 215: return 107; - case 213: return 87; - case 217: return 217; + case 216: return 73; + case 217: return 107; + case 215: return 87; + case 219: return 219; case 145: return 123; case 146: return 129; case 143: @@ -36196,16 +36922,16 @@ var ts; } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { return { - getIndentationForComment: function (kind, tokenIndentation) { + getIndentationForComment: function (kind, tokenIndentation, container) { switch (kind) { case 16: case 20: case 18: - return indentation + delta; + return indentation + getEffectiveDelta(delta, container); } return tokenIndentation !== -1 ? tokenIndentation : indentation; }, - getIndentationForToken: function (line, kind) { + getIndentationForToken: function (line, kind, container) { if (nodeStartLine !== line && node.decorators) { if (kind === getFirstNonDecoratorTokenOfNode(node)) { return indentation; @@ -36223,20 +36949,20 @@ var ts; case 55: return indentation; default: - return nodeStartLine !== line ? indentation + delta : indentation; + return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; } }, getIndentation: function () { return indentation; }, - getDelta: function () { return delta; }, + getDelta: function (child) { return getEffectiveDelta(delta, child); }, recomputeIndentation: function (lineAdded) { - if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { indentation += options.IndentSize; } else { indentation -= options.IndentSize; } - if (formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0)) { + if (formatting.SmartIndenter.shouldIndentChildNode(node)) { delta = options.IndentSize; } else { @@ -36245,6 +36971,9 @@ var ts; } } }; + function getEffectiveDelta(delta, child) { + return formatting.SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0; + } } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { @@ -36297,7 +37026,7 @@ var ts; if (ts.isToken(child)) { var tokenInfo = formattingScanner.readTokenInfo(child); ts.Debug.assert(tokenInfo.token.end === child.end); - consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } var effectiveParentStartLine = child.kind === 139 ? childStartLine : undecoratedParentStartLine; @@ -36342,7 +37071,7 @@ var ts; } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation) { + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; @@ -36374,10 +37103,10 @@ var ts; } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : -1; if (currentTokenInfo.leadingTrivia) { - var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation); + var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); var indentNextTokenOrTrivia = true; for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { var triviaItem = _a[_i]; @@ -36458,9 +37187,7 @@ var ts; dynamicIndentation.recomputeIndentation(true); } } - trimTrailingWhitespaces = - (rule.Operation.Action & (4 | 2)) && - rule.Flag !== 1; + trimTrailingWhitespaces = !(rule.Operation.Action & 8) && rule.Flag !== 1; } else { trimTrailingWhitespaces = true; @@ -36536,16 +37263,29 @@ var ts; if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { continue; } - var pos = lineEndPosition; - while (pos >= lineStartPosition && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { - pos--; - } - if (pos !== lineEndPosition) { - ts.Debug.assert(pos === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))); - recordDelete(pos + 1, lineEndPosition - pos); + var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + if (whitespaceStart !== -1) { + ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(whitespaceStart - 1))); + recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); } } } + function getTrailingWhitespaceStartPosition(start, end) { + var pos = end; + while (pos >= start && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== end) { + return pos + 1; + } + return -1; + } + function trimTrailingWhitespacesForRemainingRange() { + var startPosition = previousRange ? previousRange.end : originalRange.pos; + var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); + } function newTextChange(start, len, newText) { return { span: ts.createTextSpan(start, len), newText: newText }; } @@ -36592,8 +37332,8 @@ var ts; } function isSomeBlock(kind) { switch (kind) { - case 192: - case 219: + case 194: + case 221: return true; } return false; @@ -36601,11 +37341,11 @@ var ts; function getOpenTokenForList(node, list) { switch (node.kind) { case 144: - case 213: - case 173: + case 215: + case 175: case 143: case 142: - case 174: + case 176: if (node.typeParameters === list) { return 25; } @@ -36613,8 +37353,8 @@ var ts; return 17; } break; - case 168: - case 169: + case 170: + case 171: if (node.typeArguments === list) { return 25; } @@ -36723,7 +37463,7 @@ var ts; var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); } - if (precedingToken.kind === 24 && precedingToken.parent.kind !== 181) { + if (precedingToken.kind === 24 && precedingToken.parent.kind !== 183) { var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1) { return actualIndentation; @@ -36734,7 +37474,7 @@ var ts; var currentStart; var indentationDelta; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current.kind, previous ? previous.kind : 0)) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) { currentStart = getStartLineAndCharacterForNode(current, sourceFile); if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) { indentationDelta = 0; @@ -36794,7 +37534,7 @@ var ts; return actualIndentation + indentationDelta; } } - if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) { + if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { indentationDelta += options.IndentSize; } current = parent; @@ -36821,7 +37561,7 @@ var ts; } function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && - (parent.kind === 248 || !parentAndChildShareLine); + (parent.kind === 250 || !parentAndChildShareLine); if (!useActualIndentation) { return -1; } @@ -36845,7 +37585,7 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 196 && parent.elseStatement === child) { + if (parent.kind === 198 && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 80, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -36863,13 +37603,13 @@ var ts; return node.parent.typeArguments; } break; - case 165: + case 167: return node.parent.properties; - case 164: + case 166: return node.parent.elements; - case 213: - case 173: - case 174: + case 215: + case 175: + case 176: case 143: case 142: case 147: @@ -36884,8 +37624,8 @@ var ts; } break; } - case 169: - case 168: { + case 171: + case 170: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -36913,8 +37653,8 @@ var ts; if (node.kind === 18) { return -1; } - if (node.parent && (node.parent.kind === 168 || - node.parent.kind === 169) && + if (node.parent && (node.parent.kind === 170 || + node.parent.kind === 171) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); @@ -36932,10 +37672,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { + case 170: + case 171: case 168: case 169: - case 166: - case 167: node = node.expression; break; default: @@ -36989,34 +37729,35 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 195: - case 214: - case 186: - case 215: - case 217: + case 197: case 216: - case 164: - case 192: + case 188: + case 217: case 219: - case 165: + case 218: + case 166: + case 194: + case 221: + case 167: case 155: case 157: - case 220: - case 242: - case 241: - case 172: - case 166: + case 222: + case 244: + case 243: + case 174: case 168: - case 169: - case 193: - case 211: - case 227: - case 204: - case 182: - case 162: - case 161: - case 233: - case 234: + case 170: + case 171: + case 195: + case 213: + case 229: + case 206: + case 184: + case 164: + case 163: + case 237: + case 236: + case 242: case 142: case 147: case 148: @@ -37024,34 +37765,38 @@ var ts; case 152: case 153: case 160: - case 170: - case 178: + case 172: + case 180: + case 227: return true; } return false; } - function shouldIndentChildNode(parent, child) { - if (nodeContentIsAlwaysIndented(parent)) { - return true; - } - switch (parent) { - case 197: - case 198: - case 200: - case 201: + function nodeWillIndentChild(parent, child, indentByDefault) { + var childKind = child ? child.kind : 0; + switch (parent.kind) { case 199: - case 196: - case 213: - case 173: + case 200: + case 202: + case 203: + case 201: + case 198: + case 215: + case 175: case 143: - case 174: + case 176: case 144: case 145: case 146: - return child !== 192; - default: - return false; + return childKind !== 194; + case 235: + return childKind !== 239; } + return indentByDefault; + } + SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; + function shouldIndentChildNode(parent, child) { + return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); @@ -37081,7 +37826,7 @@ var ts; return undefined; }; return StringScriptSnapshot; - })(); + }()); function fromString(text) { return new StringScriptSnapshot(text); } @@ -37180,7 +37925,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(271, nodes.pos, nodes.end, 2048, this); + var list = createNode(273, nodes.pos, nodes.end, 2048, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -37257,7 +38002,7 @@ var ts; return child.kind < 135 ? child : child.getLastToken(sourceFile); }; return NodeObject; - })(); + }()); var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -37279,7 +38024,7 @@ var ts; return this.documentationComment; }; return SymbolObject; - })(); + }()); function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { var documentationComment = []; var docComments = getJsDocCommentsSeparatedByNewLines(); @@ -37304,13 +38049,13 @@ var ts; } }); } - if (declaration.kind === 218 && declaration.body.kind === 218) { + if (declaration.kind === 220 && declaration.body.kind === 220) { return; } - while (declaration.kind === 218 && declaration.parent.kind === 218) { + while (declaration.kind === 220 && declaration.parent.kind === 220) { declaration = declaration.parent; } - ts.forEach(getJsDocCommentTextRange(declaration.kind === 211 ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { + ts.forEach(getJsDocCommentTextRange(declaration.kind === 213 ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedJsDocComment) { ts.addRange(jsDocCommentParts, cleanedJsDocComment); @@ -37355,7 +38100,8 @@ var ts; return isName(pos, end, sourceFile, paramTag); } function pushDocCommentLineText(docComments, text, blankLineCount) { - while (blankLineCount--) { + while (blankLineCount) { + blankLineCount--; docComments.push(ts.textPart("")); } docComments.push(ts.textPart(text)); @@ -37552,7 +38298,7 @@ var ts; : undefined; }; return TypeObject; - })(); + }()); var SignatureObject = (function () { function SignatureObject(checker) { this.checker = checker; @@ -37576,7 +38322,7 @@ var ts; return this.documentationComment; }; return SignatureObject; - })(); + }()); var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { @@ -37622,7 +38368,7 @@ var ts; } if (declaration.name.kind === 136) { var expr = declaration.name.expression; - if (expr.kind === 166) { + if (expr.kind === 168) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -37642,7 +38388,7 @@ var ts; } function visit(node) { switch (node.kind) { - case 213: + case 215: case 143: case 142: var functionDeclaration = node; @@ -37661,30 +38407,30 @@ var ts; ts.forEachChild(node, visit); } break; - case 214: - case 215: case 216: case 217: case 218: - case 221: - case 230: - case 226: - case 221: + case 219: + case 220: case 223: - case 224: + case 232: + case 228: + case 223: + case 225: + case 226: case 145: case 146: case 155: addDeclaration(node); case 144: - case 193: - case 212: - case 161: - case 162: - case 219: + case 195: + case 214: + case 163: + case 164: + case 221: ts.forEachChild(node, visit); break; - case 192: + case 194: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } @@ -37693,30 +38439,30 @@ var ts; if (!(node.flags & 56)) { break; } - case 211: - case 163: + case 213: + case 165: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); break; } - case 247: + case 249: case 141: case 140: addDeclaration(node); break; - case 228: + case 230: if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 222: + case 224: var importClause = node.importClause; if (importClause) { if (importClause.name) { addDeclaration(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224) { + if (importClause.namedBindings.kind === 226) { addDeclaration(importClause.namedBindings); } else { @@ -37729,12 +38475,12 @@ var ts; } }; return SourceFileObject; - })(NodeObject); + }(NodeObject)); var TextChange = (function () { function TextChange() { } return TextChange; - })(); + }()); ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { @@ -37853,7 +38599,7 @@ var ts; ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; return ClassificationTypeNames; - })(); + }()); ts.ClassificationTypeNames = ClassificationTypeNames; function displayPartsToString(displayParts) { if (displayParts) { @@ -37867,14 +38613,14 @@ var ts; return false; } return ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 173) { + if (declaration.kind === 175) { return true; } - if (declaration.kind !== 211 && declaration.kind !== 213) { + if (declaration.kind !== 213 && declaration.kind !== 215) { return false; } for (var parent_8 = declaration.parent; !ts.isFunctionBlock(parent_8); parent_8 = parent_8.parent) { - if (parent_8.kind === 248 || parent_8.kind === 219) { + if (parent_8.kind === 250 || parent_8.kind === 221) { return false; } } @@ -37949,7 +38695,7 @@ var ts; return file && file.scriptSnapshot; }; return HostCache; - })(); + }()); var SyntaxTreeCache = (function () { function SyntaxTreeCache(host) { this.host = host; @@ -37977,7 +38723,7 @@ var ts; return this.currentSourceFile; }; return SyntaxTreeCache; - })(); + }()); function setSourceFileFields(sourceFile, scriptSnapshot, version) { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; @@ -38005,7 +38751,7 @@ var ts; sourceMapText = text; } else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name); + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); outputText = text; } }, @@ -38015,7 +38761,8 @@ var ts; getCurrentDirectory: function () { return ""; }, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; } + readFile: function (fileName) { return ""; }, + directoryExists: function (directoryExists) { return true; } }; var program = ts.createProgram([inputFileName], options, compilerHost); var diagnostics; @@ -38093,7 +38840,7 @@ var ts; var buckets = {}; var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx; + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + +"|" + settings.allowJs; } function getBucketForCompilationSettings(settings, createIfMissing) { var key = getKeyFromCompilationSettings(settings); @@ -38104,7 +38851,7 @@ var ts; return bucket; } function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = ts.lookUp(buckets, name); var sourceFiles = []; entries.forEachValue(function (key, entry) { @@ -38120,7 +38867,7 @@ var ts; sourceFiles: sourceFiles }; }); - return JSON.stringify(bucketInfoArray, null, 2); + return JSON.stringify(bucketInfoArray, undefined, 2); } function acquireDocument(fileName, compilationSettings, scriptSnapshot, version) { return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, true); @@ -38404,7 +39151,7 @@ var ts; ts.preProcessFile = preProcessFile; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 207 && referenceNode.label.text === labelName) { + if (referenceNode.kind === 209 && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -38413,16 +39160,16 @@ var ts; } function isJumpStatementTarget(node) { return node.kind === 69 && - (node.parent.kind === 203 || node.parent.kind === 202) && + (node.parent.kind === 205 || node.parent.kind === 204) && node.parent.label === node; } function isLabelOfLabeledStatement(node) { return node.kind === 69 && - node.parent.kind === 207 && + node.parent.kind === 209 && node.parent.label === node; } function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 207; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 209; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -38436,22 +39183,22 @@ var ts; return node.parent.kind === 135 && node.parent.right === node; } function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 166 && node.parent.name === node; + return node && node.parent && node.parent.kind === 168 && node.parent.name === node; } function isCallExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 168 && node.parent.expression === node; + return node && node.parent && node.parent.kind === 170 && node.parent.expression === node; } function isNewExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 169 && node.parent.expression === node; + return node && node.parent && node.parent.kind === 171 && node.parent.expression === node; } function isNameOfModuleDeclaration(node) { - return node.parent.kind === 218 && node.parent.name === node; + return node.parent.kind === 220 && node.parent.name === node; } function isNameOfFunctionDeclaration(node) { return node.kind === 69 && @@ -38459,22 +39206,22 @@ var ts; } function isNameOfPropertyAssignment(node) { return (node.kind === 69 || node.kind === 9 || node.kind === 8) && - (node.parent.kind === 245 || node.parent.kind === 246) && node.parent.name === node; + (node.parent.kind === 247 || node.parent.kind === 248) && node.parent.name === node; } function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 9 || node.kind === 8) { switch (node.parent.kind) { case 141: case 140: - case 245: case 247: + case 249: case 143: case 142: case 145: case 146: - case 218: + case 220: return node.parent.name === node; - case 167: + case 169: return node.parent.argumentExpression === node; } } @@ -38527,17 +39274,17 @@ var ts; return undefined; } switch (node.kind) { - case 248: + case 250: case 143: case 142: - case 213: - case 173: + case 215: + case 175: case 145: case 146: - case 214: - case 215: + case 216: case 217: - case 218: + case 219: + case 220: return node; } } @@ -38545,18 +39292,18 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 218: return ScriptElementKind.moduleElement; - case 214: return ScriptElementKind.classElement; - case 215: return ScriptElementKind.interfaceElement; - case 216: return ScriptElementKind.typeElement; - case 217: return ScriptElementKind.enumElement; - case 211: + case 220: return ScriptElementKind.moduleElement; + case 216: return ScriptElementKind.classElement; + case 217: return ScriptElementKind.interfaceElement; + case 218: return ScriptElementKind.typeElement; + case 219: return ScriptElementKind.enumElement; + case 213: return ts.isConst(node) ? ScriptElementKind.constElement : ts.isLet(node) ? ScriptElementKind.letElement : ScriptElementKind.variableElement; - case 213: return ScriptElementKind.functionElement; + case 215: return ScriptElementKind.functionElement; case 145: return ScriptElementKind.memberGetAccessorElement; case 146: return ScriptElementKind.memberSetAccessorElement; case 143: @@ -38570,13 +39317,13 @@ var ts; case 147: return ScriptElementKind.callSignatureElement; case 144: return ScriptElementKind.constructorImplementationElement; case 137: return ScriptElementKind.typeParameterElement; - case 247: return ScriptElementKind.variableElement; + case 249: return ScriptElementKind.variableElement; case 138: return (node.flags & 56) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 221: - case 226: case 223: - case 230: - case 224: + case 228: + case 225: + case 232: + case 226: return ScriptElementKind.alias; } return ScriptElementKind.unknown; @@ -38595,7 +39342,7 @@ var ts; } }; return CancellationTokenObject; - })(); + }()); function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -38648,7 +39395,8 @@ var ts; (oldSettings.target !== newSettings.target || oldSettings.module !== newSettings.module || oldSettings.noResolve !== newSettings.noResolve || - oldSettings.jsx !== newSettings.jsx); + oldSettings.jsx !== newSettings.jsx || + oldSettings.allowJs !== newSettings.allowJs); var compilerHost = { getSourceFile: getOrCreateSourceFile, getCancellationToken: function () { return cancellationToken; }, @@ -38665,6 +39413,10 @@ var ts; readFile: function (fileName) { var entry = hostCache.getOrCreateEntry(fileName); return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + }, + directoryExists: function (directoryName) { + ts.Debug.assert(!host.resolveModuleNames); + return ts.directoryProbablyExists(directoryName, host); } }; if (host.resolveModuleNames) { @@ -38699,8 +39451,11 @@ var ts; return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); } function sourceFileUpToDate(sourceFile) { + if (!sourceFile) { + return false; + } var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); - return sourceFile && sourceFile.version === hostCache.getVersion(path); + return sourceFile.version === hostCache.getVersion(path); } function programUpToDate() { if (!program) { @@ -38739,9 +39494,6 @@ var ts; function getSemanticDiagnostics(fileName) { synchronizeHostData(); var targetSourceFile = getValidSourceFile(fileName); - if (ts.isSourceFileJavaScript(targetSourceFile)) { - return getJavaScriptSemanticDiagnostics(targetSourceFile); - } var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); if (!program.getCompilerOptions().declaration) { return semanticDiagnostics; @@ -38749,150 +39501,6 @@ var ts; var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return ts.concatenate(semanticDiagnostics, declarationDiagnostics); } - function getJavaScriptSemanticDiagnostics(sourceFile) { - var diagnostics = []; - walk(sourceFile); - return diagnostics; - function walk(node) { - if (!node) { - return false; - } - switch (node.kind) { - case 221: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case 227: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; - case 214: - var classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case 243: - var heritageClause = node; - if (heritageClause.token === 106) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 215: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 218: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 216: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; - case 143: - case 142: - case 144: - case 145: - case 146: - case 173: - case 213: - case 174: - case 213: - var functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; - } - break; - case 193: - var variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; - case 211: - var variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; - } - break; - case 168: - case 169: - var expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - 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 138: - var parameter = node; - if (parameter.modifiers) { - 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) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, '?')); - return true; - } - if (parameter.type) { - diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 141: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 217: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 171: - var typeAssertionExpression = node; - diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); - return true; - case 139: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); - return true; - } - return ts.forEachChild(node, walk); - } - function checkTypeParameters(typeParameters) { - if (typeParameters) { - 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; - } - function checkTypeAnnotation(type) { - if (type) { - diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkModifiers(modifiers) { - if (modifiers) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 112: - case 110: - case 111: - case 122: - diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - return true; - case 113: - case 82: - case 74: - case 77: - case 115: - } - } - } - return false; - } - } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); @@ -38916,20 +39524,14 @@ var ts; return undefined; } if (performCharacterChecks) { - if (!ts.isIdentifierStart(name.charCodeAt(0), target)) { + if (!ts.isIdentifier(name, target)) { return undefined; } - for (var i = 1, n = name.length; i < n; i++) { - if (!ts.isIdentifierPart(name.charCodeAt(i), target)) { - return undefined; - } - } } return name; } function getCompletionData(fileName, position) { var typeChecker = program.getTypeChecker(); - var syntacticStart = new Date().getTime(); var sourceFile = getValidSourceFile(fileName); var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var isJsDocTagName = false; @@ -38950,9 +39552,9 @@ var ts; isJsDocTagName = true; } switch (tag.kind) { + case 271: case 269: - case 267: - case 268: + case 270: var tagWithExpression = tag; if (tagWithExpression.typeExpression) { insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; @@ -38973,9 +39575,9 @@ var ts; log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); var contextToken = previousToken; if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_3 = new Date().getTime(); + var start_6 = new Date().getTime(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_3)); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_6)); } var node = currentToken; var isRightOfDot = false; @@ -38989,7 +39591,7 @@ var ts; } var parent_9 = contextToken.parent, kind = contextToken.kind; if (kind === 21) { - if (parent_9.kind === 166) { + if (parent_9.kind === 168) { node = contextToken.parent.expression; isRightOfDot = true; } @@ -39006,7 +39608,7 @@ var ts; isRightOfOpenTag = true; location = contextToken; } - else if (kind === 39 && contextToken.parent.kind === 237) { + else if (kind === 39 && contextToken.parent.kind === 239) { isStartingCloseTag = true; } } @@ -39045,7 +39647,7 @@ var ts; function getTypeScriptMemberSymbols() { isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 69 || node.kind === 135 || node.kind === 166) { + if (node.kind === 69 || node.kind === 135 || node.kind === 168) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol && symbol.flags & 8388608) { symbol = typeChecker.getAliasedSymbol(symbol); @@ -39091,7 +39693,7 @@ var ts; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType; - if ((jsxContainer.kind === 234) || (jsxContainer.kind === 235)) { + if ((jsxContainer.kind === 236) || (jsxContainer.kind === 237)) { attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); @@ -39131,15 +39733,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 236) { + if (contextToken.kind === 238) { return true; } if (contextToken.kind === 27 && contextToken.parent) { - if (contextToken.parent.kind === 235) { + if (contextToken.parent.kind === 237) { return true; } - if (contextToken.parent.kind === 237 || contextToken.parent.kind === 234) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 233; + if (contextToken.parent.kind === 239 || contextToken.parent.kind === 236) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 235; } } return false; @@ -39149,36 +39751,36 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 24: - return containingNodeKind === 168 + return containingNodeKind === 170 || containingNodeKind === 144 - || containingNodeKind === 169 - || containingNodeKind === 164 - || containingNodeKind === 181 + || containingNodeKind === 171 + || containingNodeKind === 166 + || containingNodeKind === 183 || containingNodeKind === 152; case 17: - return containingNodeKind === 168 + return containingNodeKind === 170 || containingNodeKind === 144 - || containingNodeKind === 169 - || containingNodeKind === 172 + || containingNodeKind === 171 + || containingNodeKind === 174 || containingNodeKind === 160; case 19: - return containingNodeKind === 164 + return containingNodeKind === 166 || containingNodeKind === 149 || containingNodeKind === 136; case 125: case 126: return true; case 21: - return containingNodeKind === 218; + return containingNodeKind === 220; case 15: - return containingNodeKind === 214; + return containingNodeKind === 216; case 56: - return containingNodeKind === 211 - || containingNodeKind === 181; + return containingNodeKind === 213 + || containingNodeKind === 183; case 12: - return containingNodeKind === 183; + return containingNodeKind === 185; case 13: - return containingNodeKind === 190; + return containingNodeKind === 192; case 112: case 110: case 111: @@ -39195,11 +39797,12 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 + || contextToken.kind === 162 || contextToken.kind === 10 || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_4 = contextToken.getStart(); + var start_7 = contextToken.getStart(); var end = contextToken.getEnd(); - if (start_4 < position && position < end) { + if (start_7 < position && position < end) { return true; } if (position === end) { @@ -39213,12 +39816,12 @@ var ts; isMemberCompletion = true; var typeForObject; var existingMembers; - if (objectLikeContainer.kind === 165) { + if (objectLikeContainer.kind === 167) { isNewIdentifierLocation = true; typeForObject = typeChecker.getContextualType(objectLikeContainer); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 161) { + else if (objectLikeContainer.kind === 163) { isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (ts.isVariableLike(rootDeclaration)) { @@ -39244,9 +39847,9 @@ var ts; return true; } function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 225 ? - 222 : - 228; + var declarationKind = namedImportsOrExports.kind === 227 ? + 224 : + 230; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -39268,7 +39871,7 @@ var ts; case 15: case 24: var parent_10 = contextToken.parent; - if (parent_10 && (parent_10.kind === 165 || parent_10.kind === 161)) { + if (parent_10 && (parent_10.kind === 167 || parent_10.kind === 163)) { return parent_10; } break; @@ -39282,8 +39885,8 @@ var ts; case 15: case 24: switch (contextToken.parent.kind) { - case 225: - case 229: + case 227: + case 231: return contextToken.parent; } } @@ -39297,28 +39900,28 @@ var ts; case 26: case 39: case 69: - case 238: - case 239: - if (parent_11 && (parent_11.kind === 234 || parent_11.kind === 235)) { + case 240: + case 241: + if (parent_11 && (parent_11.kind === 236 || parent_11.kind === 237)) { return parent_11; } - else if (parent_11.kind === 238) { + else if (parent_11.kind === 240) { return parent_11.parent; } break; case 9: - if (parent_11 && ((parent_11.kind === 238) || (parent_11.kind === 239))) { + if (parent_11 && ((parent_11.kind === 240) || (parent_11.kind === 241))) { return parent_11.parent; } break; case 16: if (parent_11 && - parent_11.kind === 240 && + parent_11.kind === 242 && parent_11.parent && - (parent_11.parent.kind === 238)) { + (parent_11.parent.kind === 240)) { return parent_11.parent.parent; } - if (parent_11 && parent_11.kind === 239) { + if (parent_11 && parent_11.kind === 241) { return parent_11.parent; } break; @@ -39328,9 +39931,9 @@ var ts; } function isFunction(kind) { switch (kind) { - case 173: - case 174: - case 213: + case 175: + case 176: + case 215: case 143: case 142: case 145: @@ -39346,54 +39949,54 @@ var ts; var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 24: - return containingNodeKind === 211 || - containingNodeKind === 212 || - containingNodeKind === 193 || - containingNodeKind === 217 || - isFunction(containingNodeKind) || + return containingNodeKind === 213 || containingNodeKind === 214 || - containingNodeKind === 186 || - containingNodeKind === 215 || - containingNodeKind === 162 || - containingNodeKind === 216; + containingNodeKind === 195 || + containingNodeKind === 219 || + isFunction(containingNodeKind) || + containingNodeKind === 216 || + containingNodeKind === 188 || + containingNodeKind === 217 || + containingNodeKind === 164 || + containingNodeKind === 218; case 21: - return containingNodeKind === 162; + return containingNodeKind === 164; case 54: - return containingNodeKind === 163; + return containingNodeKind === 165; case 19: - return containingNodeKind === 162; + return containingNodeKind === 164; case 17: - return containingNodeKind === 244 || + return containingNodeKind === 246 || isFunction(containingNodeKind); case 15: - return containingNodeKind === 217 || - containingNodeKind === 215 || + return containingNodeKind === 219 || + containingNodeKind === 217 || containingNodeKind === 155; case 23: return containingNodeKind === 140 && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 215 || + (contextToken.parent.parent.kind === 217 || contextToken.parent.parent.kind === 155); case 25: - return containingNodeKind === 214 || - containingNodeKind === 186 || - containingNodeKind === 215 || - containingNodeKind === 216 || + return containingNodeKind === 216 || + containingNodeKind === 188 || + containingNodeKind === 217 || + containingNodeKind === 218 || isFunction(containingNodeKind); case 113: return containingNodeKind === 141; case 22: return containingNodeKind === 138 || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 162); + contextToken.parent.parent.kind === 164); case 112: case 110: case 111: return containingNodeKind === 138; case 116: - return containingNodeKind === 226 || - containingNodeKind === 230 || - containingNodeKind === 224; + return containingNodeKind === 228 || + containingNodeKind === 232 || + containingNodeKind === 226; case 73: case 81: case 107: @@ -39442,8 +40045,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_35 = element.propertyName || element.name; - exisingImportsOrExports[name_35.text] = true; + var name_31 = element.propertyName || element.name; + exisingImportsOrExports[name_31.text] = true; } if (ts.isEmpty(exisingImportsOrExports)) { return exportsOfModule; @@ -39457,16 +40060,17 @@ var ts; var existingMemberNames = {}; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; - if (m.kind !== 245 && - m.kind !== 246 && - m.kind !== 163) { + if (m.kind !== 247 && + m.kind !== 248 && + m.kind !== 165 && + m.kind !== 143) { continue; } if (m.getStart() <= position && position <= m.getEnd()) { continue; } var existingName = void 0; - if (m.kind === 163 && m.propertyName) { + if (m.kind === 165 && m.propertyName) { if (m.propertyName.kind === 69) { existingName = m.propertyName.text; } @@ -39485,7 +40089,7 @@ var ts; if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } - if (attr.kind === 238) { + if (attr.kind === 240) { seenNames[attr.name.text] = true; } } @@ -39522,10 +40126,10 @@ var ts; var entries = []; var target = program.getCompilerOptions().target; var nameTable = getNameTable(sourceFile); - for (var name_36 in nameTable) { - if (!uniqueNames[name_36]) { - uniqueNames[name_36] = name_36; - var displayName = getCompletionEntryDisplayName(name_36, target, true); + for (var name_32 in nameTable) { + if (!uniqueNames[name_32]) { + uniqueNames[name_32] = name_32; + var displayName = getCompletionEntryDisplayName(name_32, target, true); if (displayName) { var entry = { name: displayName, @@ -39614,7 +40218,7 @@ var ts; function getSymbolKind(symbol, location) { var flags = symbol.getFlags(); if (flags & 32) - return ts.getDeclarationOfKind(symbol, 186) ? + return ts.getDeclarationOfKind(symbol, 188) ? ScriptElementKind.localClassElement : ScriptElementKind.classElement; if (flags & 384) return ScriptElementKind.enumElement; @@ -39710,14 +40314,14 @@ var ts; var signature; type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 166) { + if (location.parent && location.parent.kind === 168) { var right = location.parent.name; if (right === location || (right && right.getFullWidth() === 0)) { location = location.parent; } } var callExpression; - if (location.kind === 168 || location.kind === 169) { + if (location.kind === 170 || location.kind === 171) { callExpression = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { @@ -39729,7 +40333,7 @@ var ts; if (!signature && candidateSignatures.length) { signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 169 || callExpression.expression.kind === 95; + var useConstructSignatures = callExpression.kind === 171 || callExpression.expression.kind === 95; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { signature = allSignatures.length ? allSignatures[0] : undefined; @@ -39759,16 +40363,16 @@ var ts; case ScriptElementKind.letElement: case ScriptElementKind.parameterElement: case ScriptElementKind.localVariableElement: - displayParts.push(ts.punctuationPart(ts.SyntaxKind.ColonToken)); + displayParts.push(ts.punctuationPart(54)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(ts.SyntaxKind.NewKeyword)); + displayParts.push(ts.keywordPart(92)); displayParts.push(ts.spacePart()); } - if (!(type.flags & ts.TypeFlags.Anonymous)) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, ts.SymbolFormatFlags.WriteTypeParametersOrArguments)); + if (!(type.flags & 65536)) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); } - addSignatureDisplayParts(signature, allSignatures, ts.TypeFormatFlags.WriteArrowStyleSignature); + addSignatureDisplayParts(signature, allSignatures, 8); break; default: addSignatureDisplayParts(signature, allSignatures); @@ -39800,7 +40404,7 @@ var ts; } } if (symbolFlags & 32 && !hasAddedSymbolInfo) { - if (ts.getDeclarationOfKind(symbol, 186)) { + if (ts.getDeclarationOfKind(symbol, 188)) { pushTypePart(ScriptElementKind.localClassElement); } else { @@ -39840,7 +40444,7 @@ var ts; } if (symbolFlags & 1536) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 218); + var declaration = ts.getDeclarationOfKind(symbol, 220); var isNamespace = declaration && declaration.name && declaration.name.kind === 69; displayParts.push(ts.keywordPart(isNamespace ? 126 : 125)); displayParts.push(ts.spacePart()); @@ -39861,32 +40465,34 @@ var ts; writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var container = ts.getContainingFunction(location); - if (container) { - var signatureDeclaration = ts.getDeclarationOfKind(symbol, 137).parent; - var signature = typeChecker.getSignatureFromDeclaration(signatureDeclaration); - if (signatureDeclaration.kind === 148) { - displayParts.push(ts.keywordPart(92)); + var declaration = ts.getDeclarationOfKind(symbol, 137); + ts.Debug.assert(declaration !== undefined); + declaration = declaration.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); + if (declaration.kind === 148) { + displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 147 && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); + } + else { + displayParts.push(ts.keywordPart(132)); displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } - else if (signatureDeclaration.kind !== 147 && signatureDeclaration.name) { - addFullSymbolName(signatureDeclaration.symbol); - } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); - } - else { - var declaration = ts.getDeclarationOfKind(symbol, 137).parent; - displayParts.push(ts.keywordPart(132)); - displayParts.push(ts.spacePart()); - addFullSymbolName(declaration.symbol); - writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } } } if (symbolFlags & 8) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 247) { + if (declaration.kind === 249) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -39902,7 +40508,7 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 221) { + if (declaration.kind === 223) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -40032,9 +40638,10 @@ var ts; if (!symbol) { switch (node.kind) { case 69: - case 166: + case 168: case 135: case 97: + case 161: case 95: var type = typeChecker.getTypeAtLocation(node); if (type) { @@ -40108,7 +40715,7 @@ var ts; var definition; ts.forEach(signatureDeclarations, function (d) { if ((selectConstructors && d.kind === 144) || - (!selectConstructors && (d.kind === 213 || d.kind === 143 || d.kind === 142))) { + (!selectConstructors && (d.kind === 215 || d.kind === 143 || d.kind === 142))) { declarations.push(d); if (d.body) definition = d; @@ -40163,7 +40770,7 @@ var ts; symbol = typeChecker.getAliasedSymbol(symbol); } } - if (node.parent.kind === 246) { + if (node.parent.kind === 248) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -40236,6 +40843,7 @@ var ts; function getSemanticDocumentHighlights(node) { if (node.kind === 69 || node.kind === 97 || + node.kind === 161 || node.kind === 95 || isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) { @@ -40287,58 +40895,58 @@ var ts; switch (node.kind) { case 88: case 80: - if (hasKind(node.parent, 196)) { + if (hasKind(node.parent, 198)) { return getIfElseOccurrences(node.parent); } break; case 94: - if (hasKind(node.parent, 204)) { + if (hasKind(node.parent, 206)) { return getReturnOccurrences(node.parent); } break; case 98: - if (hasKind(node.parent, 208)) { + if (hasKind(node.parent, 210)) { return getThrowOccurrences(node.parent); } break; case 72: - if (hasKind(parent(parent(node)), 209)) { + if (hasKind(parent(parent(node)), 211)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; case 100: case 85: - if (hasKind(parent(node), 209)) { + if (hasKind(parent(node), 211)) { return getTryCatchFinallyOccurrences(node.parent); } break; case 96: - if (hasKind(node.parent, 206)) { + if (hasKind(node.parent, 208)) { return getSwitchCaseDefaultOccurrences(node.parent); } break; case 71: case 77: - if (hasKind(parent(parent(parent(node))), 206)) { + if (hasKind(parent(parent(parent(node))), 208)) { return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); } break; case 70: case 75: - if (hasKind(node.parent, 203) || hasKind(node.parent, 202)) { + if (hasKind(node.parent, 205) || hasKind(node.parent, 204)) { return getBreakOrContinueStatementOccurrences(node.parent); } break; case 86: - if (hasKind(node.parent, 199) || - hasKind(node.parent, 200) || - hasKind(node.parent, 201)) { + if (hasKind(node.parent, 201) || + hasKind(node.parent, 202) || + hasKind(node.parent, 203)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 104: case 79: - if (hasKind(node.parent, 198) || hasKind(node.parent, 197)) { + if (hasKind(node.parent, 200) || hasKind(node.parent, 199)) { return getLoopBreakContinueOccurrences(node.parent); } break; @@ -40354,8 +40962,8 @@ var ts; } break; default: - if (ts.isModifier(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 193)) { + if (ts.isModifierKind(node.kind) && node.parent && + (ts.isDeclaration(node.parent) || node.parent.kind === 195)) { return getModifierOccurrences(node.kind, node.parent); } } @@ -40367,10 +40975,10 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 208) { + if (node.kind === 210) { statementAccumulator.push(node); } - else if (node.kind === 209) { + else if (node.kind === 211) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -40391,10 +40999,10 @@ var ts; var child = throwStatement; while (child.parent) { var parent_12 = child.parent; - if (ts.isFunctionBlock(parent_12) || parent_12.kind === 248) { + if (ts.isFunctionBlock(parent_12) || parent_12.kind === 250) { return parent_12; } - if (parent_12.kind === 209) { + if (parent_12.kind === 211) { var tryStatement = parent_12; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; @@ -40409,7 +41017,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 203 || node.kind === 202) { + if (node.kind === 205 || node.kind === 204) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -40424,15 +41032,15 @@ var ts; function getBreakOrContinueOwner(statement) { for (var node_2 = statement.parent; node_2; node_2 = node_2.parent) { switch (node_2.kind) { - case 206: - if (statement.kind === 202) { + case 208: + if (statement.kind === 204) { continue; } - case 199: - case 200: case 201: - case 198: - case 197: + case 202: + case 203: + case 200: + case 199: if (!statement.label || isLabeledBy(node_2, statement.label.text)) { return node_2; } @@ -40449,24 +41057,24 @@ var ts; function getModifierOccurrences(modifier, declaration) { var container = declaration.parent; if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 214 || - container.kind === 186 || + if (!(container.kind === 216 || + container.kind === 188 || (declaration.kind === 138 && hasKind(container, 144)))) { return undefined; } } else if (modifier === 113) { - if (!(container.kind === 214 || container.kind === 186)) { + if (!(container.kind === 216 || container.kind === 188)) { return undefined; } } else if (modifier === 82 || modifier === 122) { - if (!(container.kind === 219 || container.kind === 248)) { + if (!(container.kind === 221 || container.kind === 250)) { return undefined; } } else if (modifier === 115) { - if (!(container.kind === 214 || declaration.kind === 214)) { + if (!(container.kind === 216 || declaration.kind === 216)) { return undefined; } } @@ -40477,8 +41085,8 @@ var ts; var modifierFlag = getFlagFromModifier(modifier); var nodes; switch (container.kind) { - case 219: - case 248: + case 221: + case 250: if (modifierFlag & 128) { nodes = declaration.members.concat(declaration); } @@ -40489,8 +41097,8 @@ var ts; case 144: nodes = container.parameters.concat(container.parent.members); break; - case 214: - case 186: + case 216: + case 188: nodes = container.members; if (modifierFlag & 56) { var constructor = ts.forEach(container.members, function (member) { @@ -40570,7 +41178,7 @@ var ts; function getLoopBreakContinueOccurrences(loopNode) { var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86, 104, 79)) { - if (loopNode.kind === 197) { + if (loopNode.kind === 199) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 104)) { @@ -40591,13 +41199,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { + case 201: + case 202: + case 203: case 199: case 200: - case 201: - case 197: - case 198: return getLoopBreakContinueOccurrences(owner); - case 206: + case 208: return getSwitchCaseDefaultOccurrences(owner); } } @@ -40647,7 +41255,7 @@ var ts; } function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); - if (!(func && hasKind(func.body, 192))) { + if (!(func && hasKind(func.body, 194))) { return undefined; } var keywords = []; @@ -40661,7 +41269,7 @@ var ts; } function getIfElseOccurrences(ifStatement) { var keywords = []; - while (hasKind(ifStatement.parent, 196) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 198) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } while (ifStatement) { @@ -40672,7 +41280,7 @@ var ts; break; } } - if (!hasKind(ifStatement.elseStatement, 196)) { + if (!hasKind(ifStatement.elseStatement, 198)) { break; } ifStatement = ifStatement.elseStatement; @@ -40776,7 +41384,7 @@ var ts; return getLabelReferencesInNode(node.parent, node); } } - if (node.kind === 97) { + if (node.kind === 97 || node.kind === 161) { return getReferencesForThisKeyword(node, sourceFiles); } if (node.kind === 95) { @@ -40801,8 +41409,8 @@ var ts; } else { var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); if (ts.lookUp(nameTable, internedName)) { @@ -40830,7 +41438,7 @@ var ts; } function isImportOrExportSpecifierImportSymbol(symbol) { return (symbol.flags & 8388608) && ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 226 || declaration.kind === 230; + return declaration.kind === 228 || declaration.kind === 232; }); } function getInternedName(symbol, location, declarations) { @@ -40843,13 +41451,13 @@ var ts; } function getSymbolScope(symbol) { var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 173 || valueDeclaration.kind === 186)) { + if (valueDeclaration && (valueDeclaration.kind === 175 || valueDeclaration.kind === 188)) { return valueDeclaration; } if (symbol.flags & (4 | 8192)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 214); + return ts.getAncestor(privateDeclaration, 216); } } if (symbol.flags & 8388608) { @@ -40858,7 +41466,7 @@ var ts; if (symbol.parent || (symbol.flags & 268435456)) { return undefined; } - var scope = undefined; + var scope; var declarations = symbol.getDeclarations(); if (declarations) { for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { @@ -40870,7 +41478,7 @@ var ts; if (scope && scope !== container) { return undefined; } - if (container.kind === 248 && !ts.isExternalModule(container)) { + if (container.kind === 250 && !ts.isExternalModule(container)) { return undefined; } scope = container; @@ -41064,19 +41672,19 @@ var ts; staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; break; - case 248: + case 250: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } - case 213: - case 173: + case 215: + case 175: break; default: return undefined; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 248) { + if (searchSpaceNode.kind === 250) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -41102,13 +41710,13 @@ var ts; ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 97) { + if (!node || (node.kind !== 97 && node.kind !== 161)) { return; } var container = ts.getThisContainer(node, false); switch (searchSpaceNode.kind) { - case 173: - case 213: + case 175: + case 215: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } @@ -41119,14 +41727,14 @@ var ts; result.push(getReferenceEntryFromNode(node)); } break; - case 186: - case 214: + case 188: + case 216: if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 64) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 248: - if (container.kind === 248 && !ts.isExternalModule(container)) { + case 250: + if (container.kind === 250 && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -41148,6 +41756,10 @@ var ts; result.push(shorthandValueSymbol); } } + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 138 && + ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); + } ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { if (rootSymbol !== symbol) { result.push(rootSymbol); @@ -41161,11 +41773,11 @@ var ts; function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { if (symbol && symbol.flags & (32 | 64)) { ts.forEach(symbol.getDeclarations(), function (declaration) { - if (declaration.kind === 214) { + if (declaration.kind === 216) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 215) { + else if (declaration.kind === 217) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -41215,17 +41827,17 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_37 = node.text; + var name_33 = node.text; if (contextualType) { if (contextualType.flags & 16384) { - var unionProperty = contextualType.getProperty(name_37); + var unionProperty = contextualType.getProperty(name_33); if (unionProperty) { return [unionProperty]; } else { var result_4 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_37); + var symbol = t.getProperty(name_33); if (symbol) { result_4.push(symbol); } @@ -41234,7 +41846,7 @@ var ts; } } else { - var symbol_1 = contextualType.getProperty(name_37); + var symbol_1 = contextualType.getProperty(name_33); if (symbol_1) { return [symbol_1]; } @@ -41279,10 +41891,10 @@ var ts; } var parent = node.parent; if (parent) { - if (parent.kind === 180 || parent.kind === 179) { + if (parent.kind === 182 || parent.kind === 181) { return true; } - else if (parent.kind === 181 && parent.left === node) { + else if (parent.kind === 183 && parent.left === node) { var operator = parent.operatorToken.kind; return 56 <= operator && operator <= 68; } @@ -41293,9 +41905,6 @@ var ts; synchronizeHostData(); return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount); } - function containErrors(diagnostics) { - return ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); - } function getEmitOutput(fileName) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -41316,32 +41925,32 @@ var ts; function getMeaningFromDeclaration(node) { switch (node.kind) { case 138: - case 211: - case 163: + case 213: + case 165: case 141: case 140: - case 245: - case 246: case 247: + case 248: + case 249: case 143: case 142: case 144: case 145: case 146: - case 213: - case 173: - case 174: - case 244: + case 215: + case 175: + case 176: + case 246: return 1; case 137: - case 215: - case 216: + case 217: + case 218: case 155: return 2; - case 214: - case 217: + case 216: + case 219: return 1 | 2; - case 218: + case 220: if (node.name.kind === 9) { return 4 | 1; } @@ -41351,14 +41960,14 @@ var ts; else { return 4; } - case 225: - case 226: - case 221: - case 222: case 227: case 228: + case 223: + case 224: + case 229: + case 230: return 1 | 2 | 4; - case 248: + case 250: return 4 | 1; } return 1 | 2 | 4; @@ -41368,8 +41977,9 @@ var ts; node = node.parent; } return node.parent.kind === 151 || - (node.parent.kind === 188 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - node.kind === 97 && !ts.isExpression(node); + (node.parent.kind === 190 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 97 && !ts.isExpression(node)) || + node.kind === 161; } function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); @@ -41377,16 +41987,16 @@ var ts; function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 166) { - while (root.parent && root.parent.kind === 166) { + if (root.parent.kind === 168) { + while (root.parent && root.parent.kind === 168) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 188 && root.parent.parent.kind === 243) { + if (!isLastClause && root.parent.kind === 190 && root.parent.parent.kind === 245) { var decl = root.parent.parent.parent; - return (decl.kind === 214 && root.parent.parent.token === 106) || - (decl.kind === 215 && root.parent.parent.token === 83); + return (decl.kind === 216 && root.parent.parent.token === 106) || + (decl.kind === 217 && root.parent.parent.token === 83); } return false; } @@ -41411,13 +42021,13 @@ var ts; ts.Debug.assert(node.kind === 69); if (node.parent.kind === 135 && node.parent.right === node && - node.parent.parent.kind === 221) { + node.parent.parent.kind === 223) { return 1 | 2 | 4; } return 4; } function getMeaningFromLocation(node) { - if (node.parent.kind === 227) { + if (node.parent.kind === 229) { return 1 | 2 | 4; } else if (isInRightSideOfImport(node)) { @@ -41451,14 +42061,16 @@ var ts; return; } switch (node.kind) { - case 166: + case 168: case 135: case 9: + case 162: case 84: case 99: case 93: case 95: case 97: + case 161: case 69: break; default: @@ -41470,7 +42082,7 @@ var ts; nodeForStartPos = nodeForStartPos.parent; } else if (isNameOfModuleDeclaration(nodeForStartPos)) { - if (nodeForStartPos.parent.parent.kind === 218 && + if (nodeForStartPos.parent.parent.kind === 220 && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { nodeForStartPos = nodeForStartPos.parent.parent.name; } @@ -41490,17 +42102,17 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); } function checkForClassificationCancellation(kind) { switch (kind) { - case 218: - case 214: + case 220: + case 216: + case 217: case 215: - case 213: cancellationToken.throwIfCancellationRequested(); } } @@ -41548,7 +42160,7 @@ var ts; return undefined; function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 218 && + return declaration.kind === 220 && ts.getModuleInstanceState(declaration) === 1; }); } @@ -41684,16 +42296,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); pos = tag.tagName.end; switch (tag.kind) { - case 267: + case 269: processJSDocParameterTag(tag); break; - case 270: + case 272: processJSDocTemplateTag(tag); break; - case 269: + case 271: processElement(tag.typeExpression); break; - case 268: + case 270: processElement(tag.typeExpression); break; } @@ -41774,16 +42386,16 @@ var ts; if (ts.isPunctuation(tokenKind)) { if (token) { if (tokenKind === 56) { - if (token.parent.kind === 211 || + if (token.parent.kind === 213 || token.parent.kind === 141 || token.parent.kind === 138) { return 5; } } - if (token.parent.kind === 181 || - token.parent.kind === 179 || - token.parent.kind === 180 || - token.parent.kind === 182) { + if (token.parent.kind === 183 || + token.parent.kind === 181 || + token.parent.kind === 182 || + token.parent.kind === 184) { return 5; } } @@ -41792,7 +42404,7 @@ var ts; else if (tokenKind === 8) { return 4; } - else if (tokenKind === 9) { + else if (tokenKind === 9 || tokenKind === 162) { return 6; } else if (tokenKind === 10) { @@ -41804,7 +42416,7 @@ var ts; else if (tokenKind === 69) { if (token) { switch (token.parent.kind) { - case 214: + case 216: if (token.parent.name === token) { return 11; } @@ -41814,17 +42426,17 @@ var ts; return 15; } return; - case 215: + case 217: if (token.parent.name === token) { return 13; } return; - case 217: + case 219: if (token.parent.name === token) { return 12; } return; - case 218: + case 220: if (token.parent.name === token) { return 14; } @@ -41834,17 +42446,17 @@ var ts; return 17; } return; - case 235: + case 237: if (token.parent.tagName === token) { return 19; } return; - case 237: + case 239: if (token.parent.tagName === token) { return 20; } return; - case 234: + case 236: if (token.parent.tagName === token) { return 21; } @@ -41948,7 +42560,6 @@ var ts; return []; } function getDocCommentTemplateAtPosition(fileName, position) { - var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; @@ -41961,16 +42572,16 @@ var ts; var commentOwner; findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 213: + case 215: case 143: case 144: - case 214: - case 193: + case 216: + case 195: break findOwner; - case 248: + case 250: return undefined; - case 218: - if (commentOwner.parent.kind === 218) { + case 220: + if (commentOwner.parent.kind === 220) { return undefined; } break findOwner; @@ -42004,7 +42615,7 @@ var ts; if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } - if (commentOwner.kind === 193) { + if (commentOwner.kind === 195) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { @@ -42014,14 +42625,14 @@ var ts; return emptyArray; } function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 172) { + while (rightHandSide.kind === 174) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 173: - case 174: + case 175: + case 176: return rightHandSide.parameters; - case 186: + case 188: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 144) { @@ -42102,12 +42713,16 @@ var ts; var declarations = symbol.getDeclarations(); if (declarations && declarations.length > 0) { var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); + var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); if (defaultLibFileName) { for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { var current = declarations_10[_i]; var sourceFile_2 = current.getSourceFile(); + if (!sourceFile_2) { + continue; + } var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); - if (sourceFile_2 && getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { + if (canonicalName === canonicalDefaultLibName) { return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); } } @@ -42117,10 +42732,10 @@ var ts; if (kind) { return { canRename: true, - localizedErrorMessage: undefined, - displayName: displayName, - fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kind: kind, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kindModifiers: getSymbolModifiers(symbol), triggerSpan: ts.createTextSpan(node.getStart(), node.getWidth()) }; @@ -42200,7 +42815,7 @@ var ts; case 9: case 8: if (ts.isDeclarationName(node) || - node.parent.kind === 232 || + node.parent.kind === 234 || isArgumentOfElementAccessExpression(node)) { nameTable[node.text] = node.text; } @@ -42213,7 +42828,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 167 && + node.parent.kind === 169 && node.parent.argumentExpression === node; } function createClassifier() { @@ -42301,7 +42916,7 @@ var ts; } switch (lexState) { case 3: - text = '"\\\n' + text; + text = "\"\\\n" + text; offset = 3; break; case 2: @@ -42395,7 +43010,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9) { + if (token === 9 || token === 162) { var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { var lastCharIndex = tokenText.length - 1; @@ -42525,6 +43140,7 @@ var ts; case 8: return 4; case 9: + case 162: return 6; case 10: return 7; @@ -42681,9 +43297,6 @@ var ts; this.byteLength = byteLength; this.hrtime = hrtime; this.logger = logger; - this.pendingOperation = false; - this.fileHash = {}; - this.nextFileId = 1; this.changeSeq = 0; this.handlers = (_a = {}, _a[CommandNames.Exit] = function () { @@ -42708,7 +43321,7 @@ var ts; }, _a[CommandNames.Open] = function (request) { var openArgs = request.arguments; - _this.openClientFile(openArgs.file); + _this.openClientFile(openArgs.file, openArgs.fileContent); return { responseRequired: false }; }, _a[CommandNames.Quickinfo] = function (request) { @@ -42888,10 +43501,6 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.errorCheck = function (file, project) { - this.syntacticCheck(file, project); - this.semanticCheck(file, project); - }; Session.prototype.reloadProjects = function () { this.projectService.reloadProjects(); }; @@ -42922,7 +43531,8 @@ var ts; var index = 0; var checkOne = function () { if (matchSeq(seq)) { - var checkSpec = checkList[index++]; + var checkSpec = checkList[index]; + index++; if (checkSpec.project.getSourceFileFromName(checkSpec.fileName, requireOpen)) { _this.syntacticCheck(checkSpec.fileName, checkSpec.project); _this.immediateId = setImmediate(function () { @@ -43141,9 +43751,9 @@ var ts; symbolDisplayString: displayString }; }; - Session.prototype.openClientFile = function (fileName) { + Session.prototype.openClientFile = function (fileName, fileContent) { var file = ts.normalizePath(fileName); - this.projectService.openClientFile(file); + this.projectService.openClientFile(file, fileContent); }; Session.prototype.getQuickInfo = function (line, offset, fileName) { var file = ts.normalizePath(fileName); @@ -43454,7 +44064,7 @@ var ts; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var _a = this.getProjectInfo(fileName, true), configFileName = _a.configFileName, fileNames = _a.fileNames; + var fileNames = this.getProjectInfo(fileName, true).fileNames; var fileNamesInProject = fileNames.filter(function (value, index, array) { return value.indexOf("lib.d.ts") < 0; }); var highPriorityFiles = []; var mediumPriorityFiles = []; @@ -43546,7 +44156,7 @@ var ts; } }; return Session; - })(); + }()); server.Session = Session; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); @@ -43608,7 +44218,7 @@ var ts; return this.snap().getChangeRange(oldSnapshot); }; return ScriptInfo; - })(); + }()); server.ScriptInfo = ScriptInfo; var LSHost = (function () { function LSHost(host, project) { @@ -43621,7 +44231,8 @@ var ts; this.filenameToScript = ts.createFileMap(); this.moduleResolutionHost = { fileExists: function (fileName) { return _this.fileExists(fileName); }, - readFile: function (fileName) { return _this.host.readFile(fileName); } + readFile: function (fileName) { return _this.host.readFile(fileName); }, + directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } }; } LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { @@ -43748,12 +44359,10 @@ var ts; throw new Error("No script with name '" + filename + "'"); }; LSHost.prototype.resolvePath = function (path) { - var start = new Date().getTime(); var result = this.host.resolvePath(path); return result; }; LSHost.prototype.fileExists = function (path) { - var start = new Date().getTime(); var result = this.host.fileExists(path); return result; }; @@ -43790,32 +44399,8 @@ var ts; return { line: lineOffset.line, offset: lineOffset.offset + 1 }; }; return LSHost; - })(); + }()); server.LSHost = LSHost; - function getAbsolutePath(filename, directory) { - var rootLength = ts.getRootLength(filename); - if (rootLength > 0) { - return filename; - } - else { - var splitFilename = filename.split("/"); - var splitDir = directory.split("/"); - var i = 0; - var dirTail = 0; - var sflen = splitFilename.length; - while ((i < sflen) && (splitFilename[i].charAt(0) == ".")) { - var dots = splitFilename[i]; - if (dots == "..") { - dirTail++; - } - else if (dots != ".") { - return undefined; - } - i++; - } - return splitDir.slice(0, splitDir.length - dirTail).concat(splitFilename.slice(i)).join("/"); - } - } var Project = (function () { function Project(projectService, projectOptions) { this.projectService = projectService; @@ -43902,7 +44487,7 @@ var ts; } }; return Project; - })(); + }()); server.Project = Project; function copyListRemovingItem(item, list) { var copiedList = []; @@ -43926,7 +44511,7 @@ var ts; this.openFileRootsConfigured = []; this.directoryWatchersForTsconfig = {}; this.directoryWatchersRefCount = {}; - this.timerForDetectingProjectFilelistChanges = {}; + this.timerForDetectingProjectFileListChanges = {}; this.addDefaultHostConfiguration(); } ProjectService.prototype.addDefaultHostConfiguration = function () { @@ -43959,22 +44544,22 @@ var ts; } }; ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) { - if (fileName && !ts.isSupportedSourceFileName(fileName)) { + if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) { return; } this.log("Detected source file changes: " + fileName); - this.startTimerForDetectingProjectFilelistChanges(project); + this.startTimerForDetectingProjectFileListChanges(project); }; - ProjectService.prototype.startTimerForDetectingProjectFilelistChanges = function (project) { + ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) { var _this = this; - if (this.timerForDetectingProjectFilelistChanges[project.projectFilename]) { - clearTimeout(this.timerForDetectingProjectFilelistChanges[project.projectFilename]); + if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) { + clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]); } - this.timerForDetectingProjectFilelistChanges[project.projectFilename] = setTimeout(function () { return _this.handleProjectFilelistChanges(project); }, 250); + this.timerForDetectingProjectFileListChanges[project.projectFilename] = setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250); }; - ProjectService.prototype.handleProjectFilelistChanges = function (project) { + ProjectService.prototype.handleProjectFileListChanges = function (project) { var _this = this; - var _a = this.configFileToProjectOptions(project.projectFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, error = _a.error; + var projectOptions = this.configFileToProjectOptions(project.projectFilename).projectOptions; 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())) { @@ -43989,7 +44574,7 @@ var ts; return; } this.log("Detected newly added tsconfig file: " + fileName); - var _a = this.configFileToProjectOptions(fileName), succeeded = _a.succeeded, projectOptions = _a.projectOptions, error = _a.error; + var projectOptions = this.configFileToProjectOptions(fileName).projectOptions; 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++) { @@ -44108,7 +44693,8 @@ var ts; else { for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { var directory = _a[_i]; - if (!(--project.projectService.directoryWatchersRefCount[directory])) { + project.projectService.directoryWatchersRefCount[directory]--; + if (!project.projectService.directoryWatchersRefCount[directory]) { this.log("Close directory watcher for: " + directory); project.projectService.directoryWatchersForTsconfig[directory].close(); delete project.projectService.directoryWatchersForTsconfig[directory]; @@ -44308,14 +44894,14 @@ var ts; filename = ts.normalizePath(filename); return ts.lookUp(this.filenameToScriptInfo, filename); }; - ProjectService.prototype.openFile = function (fileName, openedByClient) { + ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent) { var _this = this; fileName = ts.normalizePath(fileName); var info = ts.lookUp(this.filenameToScriptInfo, fileName); if (!info) { var content; if (this.host.fileExists(fileName)) { - content = this.host.readFile(fileName); + content = fileContent || this.host.readFile(fileName); } if (!content) { if (openedByClient) { @@ -44332,6 +44918,9 @@ var ts; } } if (info) { + if (fileContent) { + info.svc.reload(fileContent); + } if (openedByClient) { info.isOpen = true; } @@ -44352,9 +44941,9 @@ var ts; } return undefined; }; - ProjectService.prototype.openClientFile = function (fileName) { + ProjectService.prototype.openClientFile = function (fileName, fileContent) { this.openOrUpdateConfiguredProjectForFile(fileName); - var info = this.openFile(fileName, true); + var info = this.openFile(fileName, true, fileContent); this.addOpenFile(info); this.printProjects(); return info; @@ -44568,7 +45157,7 @@ var ts; return project; }; return ProjectService; - })(); + }()); server.ProjectService = ProjectService; var CompilerService = (function () { function CompilerService(project, opt) { @@ -44607,11 +45196,12 @@ var ts; InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, PlaceOpenBraceOnNewLineForFunctions: false, PlaceOpenBraceOnNewLineForControlBlocks: false }; return CompilerService; - })(); + }()); server.CompilerService = CompilerService; (function (CharRangeSection) { CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; @@ -44630,7 +45220,7 @@ var ts; BaseLineIndexWalker.prototype.leaf = function (rangeStart, rangeLength, ll) { }; return BaseLineIndexWalker; - })(); + }()); var EditWalker = (function (_super) { __extends(EditWalker, _super); function EditWalker() { @@ -44814,7 +45404,7 @@ var ts; } }; return EditWalker; - })(BaseLineIndexWalker); + }(BaseLineIndexWalker)); var TextChange = (function () { function TextChange(pos, deleteLen, insertedText) { this.pos = pos; @@ -44825,7 +45415,7 @@ var ts; return ts.createTextChangeRange(ts.createTextSpan(this.pos, this.deleteLen), this.insertedText ? this.insertedText.length : 0); }; return TextChange; - })(); + }()); server.TextChange = TextChange; var ScriptVersionCache = (function () { function ScriptVersionCache() { @@ -44929,7 +45519,7 @@ var ts; ScriptVersionCache.changeLengthThreshold = 256; ScriptVersionCache.maxVersions = 8; return ScriptVersionCache; - })(); + }()); server.ScriptVersionCache = ScriptVersionCache; var LineIndexSnapshot = (function () { function LineIndexSnapshot(version, cache) { @@ -44948,7 +45538,8 @@ var ts; var count = 1; var pos = 0; this.index.every(function (ll, s, len) { - starts[count++] = pos; + starts[count] = pos; + count++; pos += ll.text.length; return true; }, 0); @@ -44956,9 +45547,9 @@ var ts; }; LineIndexSnapshot.prototype.getLineMapper = function () { var _this = this; - return (function (line) { + return function (line) { return _this.index.lineNumberToInfo(line).offset; - }); + }; }; LineIndexSnapshot.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { if (this.version <= scriptVersion) { @@ -44973,7 +45564,7 @@ var ts; return this.getTextChangeRangeSinceVersion(oldSnap.version); }; return LineIndexSnapshot; - })(); + }()); server.LineIndexSnapshot = LineIndexSnapshot; var LineIndex = (function () { function LineIndex() { @@ -45145,7 +45736,7 @@ var ts; return { lines: lines, lineMap: lineStarts }; }; return LineIndex; - })(); + }()); server.LineIndex = LineIndex; var LineNode = (function () { function LineNode() { @@ -45194,7 +45785,8 @@ var ts; while (adjustedStart >= childCharCount) { this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, CharRangeSection.PreStart); adjustedStart -= childCharCount; - child = this.children[++childIndex]; + childIndex++; + child = this.children[childIndex]; childCharCount = child.charCount(); } if ((adjustedStart + rangeLength) <= childCharCount) { @@ -45207,14 +45799,16 @@ var ts; return; } var adjustedLength = rangeLength - (childCharCount - adjustedStart); - child = this.children[++childIndex]; + childIndex++; + child = this.children[childIndex]; childCharCount = child.charCount(); while (adjustedLength > childCharCount) { if (this.execWalk(0, childCharCount, walkFns, childIndex, CharRangeSection.Mid)) { return; } adjustedLength -= childCharCount; - child = this.children[++childIndex]; + childIndex++; + child = this.children[childIndex]; childCharCount = child.charCount(); } if (adjustedLength > 0) { @@ -45332,7 +45926,8 @@ var ts; if (childIndex < clen) { splitNode = new LineNode(); while (childIndex < clen) { - splitNode.add(this.children[childIndex++]); + splitNode.add(this.children[childIndex]); + childIndex++; } splitNode.updateCounts(); } @@ -45370,7 +45965,9 @@ var ts; var nodeIndex = 0; childIndex++; while ((childIndex < lineCollectionCapacity) && (nodeIndex < nodeCount)) { - this.children[childIndex++] = nodes[nodeIndex++]; + this.children[childIndex] = nodes[nodeIndex]; + childIndex++; + nodeIndex++; } var splitNodes = []; var splitNodeCount = 0; @@ -45383,7 +45980,8 @@ var ts; } var splitNode = splitNodes[0]; while (nodeIndex < nodeCount) { - splitNode.add(nodes[nodeIndex++]); + splitNode.add(nodes[nodeIndex]); + nodeIndex++; if (splitNode.children.length === lineCollectionCapacity) { splitNodeIndex++; splitNode = splitNodes[splitNodeIndex]; @@ -45416,7 +46014,7 @@ var ts; return this.totalLines; }; return LineNode; - })(); + }()); server.LineNode = LineNode; var LineLeaf = (function () { function LineLeaf(text) { @@ -45441,7 +46039,7 @@ var ts; return 1; }; return LineLeaf; - })(); + }()); server.LineLeaf = LineLeaf; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); @@ -45449,9 +46047,7 @@ var ts; (function (ts) { var server; (function (server) { - var nodeproto = require("_debugger"); var readline = require("readline"); - var path = require("path"); var fs = require("fs"); var rl = readline.createInterface({ input: process.stdin, @@ -45519,7 +46115,7 @@ var ts; } }; return Logger; - })(); + }()); var IOSession = (function (_super) { __extends(IOSession, _super); function IOSession(host, logger) { @@ -45541,7 +46137,7 @@ var ts; }); }; return IOSession; - })(server.Session); + }(server.Session)); function parseLoggingEnvironmentString(logEnvStr) { var logEnv = {}; var args = logEnvStr.split(" "); @@ -45616,7 +46212,6 @@ var ts; var ScriptSnapshotShimAdapter = (function () { function ScriptSnapshotShimAdapter(scriptSnapshotShim) { this.scriptSnapshotShim = scriptSnapshotShim; - this.lineStartPositions = null; } ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { return this.scriptSnapshotShim.getText(start, end); @@ -45639,7 +46234,7 @@ var ts; } }; return ScriptSnapshotShimAdapter; - })(); + }()); var LanguageServiceShimHostAdapter = (function () { function LanguageServiceShimHostAdapter(shimHost) { var _this = this; @@ -45655,6 +46250,9 @@ var ts; }); }; } + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } LanguageServiceShimHostAdapter.prototype.log = function (s) { if (this.loggingEnabled) { @@ -45690,9 +46288,6 @@ var ts; return this.files = JSON.parse(encoded); }; LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { - if (this.files && this.files.indexOf(fileName) < 0) { - return undefined; - } var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); }; @@ -45720,15 +46315,10 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { - try { - return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); - } - catch (e) { - return ""; - } + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; return LanguageServiceShimHostAdapter; - })(); + }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; var ThrottledCancellationToken = (function () { function ThrottledCancellationToken(hostCancellationToken) { @@ -45745,19 +46335,17 @@ var ts; return false; }; return ThrottledCancellationToken; - })(); + }()); var CoreServicesShimHostAdapter = (function () { function CoreServicesShimHostAdapter(shimHost) { + var _this = this; this.shimHost = shimHost; + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude) { - var encoded; - try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); - } - catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension); - } + var encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -45767,18 +46355,19 @@ var ts; return this.shimHost.readFile(fileName); }; return CoreServicesShimHostAdapter; - })(); + }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; function simpleForwardCall(logger, actionDescription, action, logPerformance) { + var start; if (logPerformance) { logger.log(actionDescription); - var start = Date.now(); + start = Date.now(); } var result = action(); if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); - if (typeof (result) === "string") { + if (typeof result === "string") { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; @@ -45811,7 +46400,7 @@ var ts; this.factory.unregisterShim(this); }; return ShimBase; - })(); + }()); function realizeDiagnostics(diagnostics, newLine) { return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); } @@ -45849,9 +46438,7 @@ var ts; _super.prototype.dispose.call(this, dummy); }; LanguageServiceShimObject.prototype.refresh = function (throwOnError) { - this.forwardJSONCall("refresh(" + throwOnError + ")", function () { - return null; - }); + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); }; LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { var _this = this; @@ -45866,29 +46453,19 @@ var ts; }; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { var _this = this; @@ -45913,62 +46490,39 @@ var ts; }; LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { - var quickInfo = _this.languageService.getQuickInfoAtPosition(fileName, position); - return quickInfo; - }); + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { var _this = this; - return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { - var spanInfo = _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); - return spanInfo; - }); + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); }; LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { - var spanInfo = _this.languageService.getBreakpointStatementAtPosition(fileName, position); - return spanInfo; - }); + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { - var signatureInfo = _this.languageService.getSignatureHelpItems(fileName, position); - return signatureInfo; - }); + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); }); }; LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getTypeDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { - return _this.languageService.getRenameInfo(fileName, position); - }); + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); }; LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { var _this = this; - return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { - return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); - }); + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); }; LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { - var textRanges = _this.languageService.getBraceMatchingAtPosition(fileName, position); - return textRanges; - }); + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options) { var _this = this; @@ -45979,21 +46533,15 @@ var ts; }; LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getReferencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { var _this = this; - return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { - return _this.languageService.findReferences(fileName, position); - }); + return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); }); }; LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getOccurrencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { var _this = this; @@ -46005,40 +46553,31 @@ var ts; }; LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { - var completion = _this.languageService.getCompletionsAtPosition(fileName, position); - return completion; - }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", " + entryName + ")", function () { - var details = _this.languageService.getCompletionEntryDetails(fileName, position, entryName); - return details; - }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options) { var _this = this; return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); - return edits; + return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options) { var _this = this; return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForDocument(fileName, localOptions); - return edits; + return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options) { var _this = this; return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); - return edits; + return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { @@ -46047,42 +46586,26 @@ var ts; }; LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount) { var _this = this; - return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { - var items = _this.languageService.getNavigateToItems(searchValue, maxResultCount); - return items; - }); + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; - return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { - var items = _this.languageService.getNavigationBarItems(fileName); - return items; - }); + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; - return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { - var items = _this.languageService.getOutliningSpans(fileName); - return items; - }); + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); }; LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { var _this = this; - return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { - var items = _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); - return items; - }); + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); }; LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { var _this = this; - return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { - var output = _this.languageService.getEmitOutput(fileName); - output.emitOutputStatus = output.emitSkipped ? 1 : 0; - return output; - }); + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); }; return LanguageServiceShimObject; - })(ShimBase); + }(ShimBase)); function convertClassifications(classifications) { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } @@ -46100,17 +46623,17 @@ var ts; }; ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); - var items = classification.entries; var result = ""; - for (var i = 0; i < items.length; i++) { - result += items[i].length + "\n"; - result += items[i].classification + "\n"; + for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { + var item = _a[_i]; + result += item.length + "\n"; + result += item.classification + "\n"; } result += classification.finalLexState; return result; }; return ClassifierShimObject; - })(ShimBase); + }(ShimBase)); var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { @@ -46168,24 +46691,22 @@ var ts; return { options: {}, files: [], - errors: [realizeDiagnostic(result.error, '\r\n')] + errors: [realizeDiagnostic(result.error, "\r\n")] }; } var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(ts.normalizeSlashes(fileName))); return { options: configFile.options, files: configFile.fileNames, - errors: realizeDiagnostics(configFile.errors, '\r\n') + errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); }; CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { - return this.forwardJSONCall("getDefaultCompilationSettings()", function () { - return ts.getDefaultCompilerOptions(); - }); + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); }); }; return CoreServicesShimObject; - })(ShimBase); + }(ShimBase)); var TypeScriptServicesFactory = (function () { function TypeScriptServicesFactory() { this._shims = []; @@ -46243,7 +46764,7 @@ var ts; throw new Error("Invalid operation"); }; return TypeScriptServicesFactory; - })(); + }()); ts.TypeScriptServicesFactory = TypeScriptServicesFactory; if (typeof module !== "undefined" && module.exports) { module.exports = ts; @@ -46256,4 +46777,4 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "1.6"; +var toolsVersion = "1.8"; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 32a6dee4623..3196ae2199f 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -194,118 +194,120 @@ declare namespace ts { UnionType = 158, IntersectionType = 159, ParenthesizedType = 160, - ObjectBindingPattern = 161, - ArrayBindingPattern = 162, - BindingElement = 163, - ArrayLiteralExpression = 164, - ObjectLiteralExpression = 165, - PropertyAccessExpression = 166, - ElementAccessExpression = 167, - CallExpression = 168, - NewExpression = 169, - TaggedTemplateExpression = 170, - TypeAssertionExpression = 171, - ParenthesizedExpression = 172, - FunctionExpression = 173, - ArrowFunction = 174, - DeleteExpression = 175, - TypeOfExpression = 176, - VoidExpression = 177, - AwaitExpression = 178, - PrefixUnaryExpression = 179, - PostfixUnaryExpression = 180, - BinaryExpression = 181, - ConditionalExpression = 182, - TemplateExpression = 183, - YieldExpression = 184, - SpreadElementExpression = 185, - ClassExpression = 186, - OmittedExpression = 187, - ExpressionWithTypeArguments = 188, - AsExpression = 189, - TemplateSpan = 190, - SemicolonClassElement = 191, - Block = 192, - VariableStatement = 193, - EmptyStatement = 194, - ExpressionStatement = 195, - IfStatement = 196, - DoStatement = 197, - WhileStatement = 198, - ForStatement = 199, - ForInStatement = 200, - ForOfStatement = 201, - ContinueStatement = 202, - BreakStatement = 203, - ReturnStatement = 204, - WithStatement = 205, - SwitchStatement = 206, - LabeledStatement = 207, - ThrowStatement = 208, - TryStatement = 209, - DebuggerStatement = 210, - VariableDeclaration = 211, - VariableDeclarationList = 212, - FunctionDeclaration = 213, - ClassDeclaration = 214, - InterfaceDeclaration = 215, - TypeAliasDeclaration = 216, - EnumDeclaration = 217, - ModuleDeclaration = 218, - ModuleBlock = 219, - CaseBlock = 220, - ImportEqualsDeclaration = 221, - ImportDeclaration = 222, - ImportClause = 223, - NamespaceImport = 224, - NamedImports = 225, - ImportSpecifier = 226, - ExportAssignment = 227, - ExportDeclaration = 228, - NamedExports = 229, - ExportSpecifier = 230, - MissingDeclaration = 231, - ExternalModuleReference = 232, - JsxElement = 233, - JsxSelfClosingElement = 234, - JsxOpeningElement = 235, - JsxText = 236, - JsxClosingElement = 237, - JsxAttribute = 238, - JsxSpreadAttribute = 239, - JsxExpression = 240, - CaseClause = 241, - DefaultClause = 242, - HeritageClause = 243, - CatchClause = 244, - PropertyAssignment = 245, - ShorthandPropertyAssignment = 246, - EnumMember = 247, - SourceFile = 248, - JSDocTypeExpression = 249, - JSDocAllType = 250, - JSDocUnknownType = 251, - JSDocArrayType = 252, - JSDocUnionType = 253, - JSDocTupleType = 254, - JSDocNullableType = 255, - JSDocNonNullableType = 256, - JSDocRecordType = 257, - JSDocRecordMember = 258, - JSDocTypeReference = 259, - JSDocOptionalType = 260, - JSDocFunctionType = 261, - JSDocVariadicType = 262, - JSDocConstructorType = 263, - JSDocThisType = 264, - JSDocComment = 265, - JSDocTag = 266, - JSDocParameterTag = 267, - JSDocReturnTag = 268, - JSDocTypeTag = 269, - JSDocTemplateTag = 270, - SyntaxList = 271, - Count = 272, + ThisType = 161, + StringLiteralType = 162, + ObjectBindingPattern = 163, + ArrayBindingPattern = 164, + BindingElement = 165, + ArrayLiteralExpression = 166, + ObjectLiteralExpression = 167, + PropertyAccessExpression = 168, + ElementAccessExpression = 169, + CallExpression = 170, + NewExpression = 171, + TaggedTemplateExpression = 172, + TypeAssertionExpression = 173, + ParenthesizedExpression = 174, + FunctionExpression = 175, + ArrowFunction = 176, + DeleteExpression = 177, + TypeOfExpression = 178, + VoidExpression = 179, + AwaitExpression = 180, + PrefixUnaryExpression = 181, + PostfixUnaryExpression = 182, + BinaryExpression = 183, + ConditionalExpression = 184, + TemplateExpression = 185, + YieldExpression = 186, + SpreadElementExpression = 187, + ClassExpression = 188, + OmittedExpression = 189, + ExpressionWithTypeArguments = 190, + AsExpression = 191, + TemplateSpan = 192, + SemicolonClassElement = 193, + Block = 194, + VariableStatement = 195, + EmptyStatement = 196, + ExpressionStatement = 197, + IfStatement = 198, + DoStatement = 199, + WhileStatement = 200, + ForStatement = 201, + ForInStatement = 202, + ForOfStatement = 203, + ContinueStatement = 204, + BreakStatement = 205, + ReturnStatement = 206, + WithStatement = 207, + SwitchStatement = 208, + LabeledStatement = 209, + ThrowStatement = 210, + TryStatement = 211, + DebuggerStatement = 212, + VariableDeclaration = 213, + VariableDeclarationList = 214, + FunctionDeclaration = 215, + ClassDeclaration = 216, + InterfaceDeclaration = 217, + TypeAliasDeclaration = 218, + EnumDeclaration = 219, + ModuleDeclaration = 220, + ModuleBlock = 221, + CaseBlock = 222, + ImportEqualsDeclaration = 223, + ImportDeclaration = 224, + ImportClause = 225, + NamespaceImport = 226, + NamedImports = 227, + ImportSpecifier = 228, + ExportAssignment = 229, + ExportDeclaration = 230, + NamedExports = 231, + ExportSpecifier = 232, + MissingDeclaration = 233, + ExternalModuleReference = 234, + JsxElement = 235, + JsxSelfClosingElement = 236, + JsxOpeningElement = 237, + JsxText = 238, + JsxClosingElement = 239, + JsxAttribute = 240, + JsxSpreadAttribute = 241, + JsxExpression = 242, + CaseClause = 243, + DefaultClause = 244, + HeritageClause = 245, + CatchClause = 246, + PropertyAssignment = 247, + ShorthandPropertyAssignment = 248, + EnumMember = 249, + SourceFile = 250, + JSDocTypeExpression = 251, + JSDocAllType = 252, + JSDocUnknownType = 253, + JSDocArrayType = 254, + JSDocUnionType = 255, + JSDocTupleType = 256, + JSDocNullableType = 257, + JSDocNonNullableType = 258, + JSDocRecordType = 259, + JSDocRecordMember = 260, + JSDocTypeReference = 261, + JSDocOptionalType = 262, + JSDocFunctionType = 263, + JSDocVariadicType = 264, + JSDocConstructorType = 265, + JSDocThisType = 266, + JSDocComment = 267, + JSDocTag = 268, + JSDocParameterTag = 269, + JSDocReturnTag = 270, + JSDocTypeTag = 271, + JSDocTemplateTag = 272, + SyntaxList = 273, + Count = 274, FirstAssignment = 56, LastAssignment = 68, FirstReservedWord = 70, @@ -314,8 +316,8 @@ declare namespace ts { LastKeyword = 134, FirstFutureReservedWord = 106, LastFutureReservedWord = 114, - FirstTypeNode = 151, - LastTypeNode = 160, + FirstTypeNode = 150, + LastTypeNode = 162, FirstPunctuation = 15, LastPunctuation = 68, FirstToken = 0, @@ -359,10 +361,14 @@ declare namespace ts { } enum JsxFlags { None = 0, + /** An element from a named property of the JSX.IntrinsicElements interface */ IntrinsicNamedElement = 1, + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, - ClassElement = 4, - UnknownElement = 8, + /** An element backed by a class, class-like, or function value */ + ValueElement = 4, + /** Element resolution failed */ + UnknownElement = 16, IntrinsicElement = 3, } interface Node extends TextRange { @@ -375,9 +381,11 @@ declare namespace ts { interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface ModifiersArray extends NodeArray { + interface ModifiersArray extends NodeArray { flags: number; } + interface Modifier extends Node { + } interface Identifier extends PrimaryExpression { text: string; originalKeywordKind?: SyntaxKind; @@ -393,6 +401,9 @@ declare namespace ts { _declarationBrand: any; name?: DeclarationName; } + interface DeclarationStatement extends Declaration, Statement { + name?: Identifier; + } interface ComputedPropertyName extends Node { expression: Expression; } @@ -405,10 +416,15 @@ declare namespace ts { expression?: Expression; } interface SignatureDeclaration extends Declaration { + name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; type?: TypeNode; } + interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + } + interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + } interface VariableDeclaration extends Declaration { parent?: VariableDeclarationList; name: Identifier | BindingPattern; @@ -431,18 +447,25 @@ declare namespace ts { name: Identifier | BindingPattern; initializer?: Expression; } - interface PropertyDeclaration extends Declaration, ClassElement { - name: DeclarationName; + interface PropertySignature extends TypeElement { + name: PropertyName; questionToken?: Node; type?: TypeNode; initializer?: Expression; } + interface PropertyDeclaration extends ClassElement { + questionToken?: Node; + name: PropertyName; + type?: TypeNode; + initializer?: Expression; + } interface ObjectLiteralElement extends Declaration { _objectLiteralBrandBrand: any; + name?: PropertyName; } interface PropertyAssignment extends ObjectLiteralElement { _propertyAssignmentBrand: any; - name: DeclarationName; + name: PropertyName; questionToken?: Node; initializer: Expression; } @@ -460,9 +483,16 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } + interface PropertyLikeDeclaration extends Declaration { + name: PropertyName; + } interface BindingPattern extends Node { elements: NodeArray; } + interface ObjectBindingPattern extends BindingPattern { + } + interface ArrayBindingPattern extends BindingPattern { + } /** * Several node kinds share function-like features such as a signature, * a name, and a body. These nodes should extend FunctionLikeDeclaration. @@ -477,45 +507,61 @@ declare namespace ts { questionToken?: Node; body?: Block | Expression; } - interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { + interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { name?: Identifier; - body?: Block; + body?: FunctionBody; + } + interface MethodSignature extends SignatureDeclaration, TypeElement { + name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - body?: Block; + name: PropertyName; + body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { - body?: Block; + body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { _semicolonClassElementBrand: any; } interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { _accessorDeclarationBrand: any; - body: Block; + name: PropertyName; + body: FunctionBody; } - interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { + interface GetAccessorDeclaration extends AccessorDeclaration { + } + interface SetAccessorDeclaration extends AccessorDeclaration { + } + interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { _indexSignatureDeclarationBrand: any; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface ThisTypeNode extends TypeNode { + _thisTypeNodeBrand: any; + } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { _functionOrConstructorTypeNodeBrand: any; } + interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + } + interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + } interface TypeReferenceNode extends TypeNode { typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { - parameterName: Identifier; + parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { - members: NodeArray; + members: NodeArray; } interface ArrayTypeNode extends TypeNode { elementType: TypeNode; @@ -533,13 +579,18 @@ declare namespace ts { interface ParenthesizedTypeNode extends TypeNode { type: TypeNode; } - interface StringLiteral extends LiteralExpression, TypeNode { + interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode { + _stringLiteralTypeBrand: any; + } + interface StringLiteral extends LiteralExpression { _stringLiteralBrand: any; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } + interface OmittedExpression extends Expression { + } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; } @@ -594,25 +645,34 @@ declare namespace ts { colonToken: Node; whenFalse: Expression; } + type FunctionBody = Block; + type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { name?: Identifier; - body: Block | Expression; + body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { equalsGreaterThanToken: Node; + body: ConciseBody; } - interface LiteralExpression extends PrimaryExpression { + interface LiteralLikeNode extends Node { text: string; isUnterminated?: boolean; hasExtendedUnicodeEscape?: boolean; } + interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { + _literalExpressionBrand: any; + } + interface TemplateLiteralFragment extends LiteralLikeNode { + _templateLiteralFragmentBrand: any; + } interface TemplateExpression extends PrimaryExpression { - head: LiteralExpression; + head: TemplateLiteralFragment; templateSpans: NodeArray; } interface TemplateSpan extends Node { expression: Expression; - literal: LiteralExpression; + literal: TemplateLiteralFragment; } interface ParenthesizedExpression extends PrimaryExpression { expression: Expression; @@ -694,6 +754,14 @@ declare namespace ts { interface Statement extends Node { _statementBrand: any; } + interface EmptyStatement extends Statement { + } + interface DebuggerStatement extends Statement { + } + interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + name?: Identifier; + } + type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { statements: NodeArray; } @@ -730,9 +798,13 @@ declare namespace ts { initializer: VariableDeclarationList | Expression; expression: Expression; } - interface BreakOrContinueStatement extends Statement { + interface BreakStatement extends Statement { label?: Identifier; } + interface ContinueStatement extends Statement { + label?: Identifier; + } + type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { expression?: Expression; } @@ -748,7 +820,7 @@ declare namespace ts { clauses: NodeArray; } interface CaseClause extends Node { - expression?: Expression; + expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { @@ -777,24 +849,31 @@ declare namespace ts { heritageClauses?: NodeArray; members: NodeArray; } - interface ClassDeclaration extends ClassLikeDeclaration, Statement { + interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { } interface ClassElement extends Declaration { _classElementBrand: any; + name?: PropertyName; } - interface InterfaceDeclaration extends Declaration, Statement { + interface TypeElement extends Declaration { + _typeElementBrand: any; + name?: PropertyName; + questionToken?: Node; + } + interface InterfaceDeclaration extends DeclarationStatement { name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; - members: NodeArray; + members: NodeArray; } interface HeritageClause extends Node { token: SyntaxKind; types?: NodeArray; } - interface TypeAliasDeclaration extends Declaration, Statement { + interface TypeAliasDeclaration extends DeclarationStatement { name: Identifier; typeParameters?: NodeArray; type: TypeNode; @@ -803,18 +882,19 @@ declare namespace ts { name: DeclarationName; initializer?: Expression; } - interface EnumDeclaration extends Declaration, Statement { + interface EnumDeclaration extends DeclarationStatement { name: Identifier; members: NodeArray; } - interface ModuleDeclaration extends Declaration, Statement { + type ModuleBody = ModuleBlock | ModuleDeclaration; + interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; body: ModuleBlock | ModuleDeclaration; } interface ModuleBlock extends Node, Statement { statements: NodeArray; } - interface ImportEqualsDeclaration extends Declaration, Statement { + interface ImportEqualsDeclaration extends DeclarationStatement { name: Identifier; moduleReference: EntityName | ExternalModuleReference; } @@ -832,22 +912,27 @@ declare namespace ts { interface NamespaceImport extends Declaration { name: Identifier; } - interface ExportDeclaration extends Declaration, Statement { + interface ExportDeclaration extends DeclarationStatement { exportClause?: NamedExports; moduleSpecifier?: Expression; } - interface NamedImportsOrExports extends Node { - elements: NodeArray; + interface NamedImports extends Node { + elements: NodeArray; } - type NamedImports = NamedImportsOrExports; - type NamedExports = NamedImportsOrExports; - interface ImportOrExportSpecifier extends Declaration { + interface NamedExports extends Node { + elements: NodeArray; + } + type NamedImportsOrExports = NamedImports | NamedExports; + interface ImportSpecifier extends Declaration { propertyName?: Identifier; name: Identifier; } - type ImportSpecifier = ImportOrExportSpecifier; - type ExportSpecifier = ImportOrExportSpecifier; - interface ExportAssignment extends Declaration, Statement { + interface ExportSpecifier extends Declaration { + propertyName?: Identifier; + name: Identifier; + } + type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; + interface ExportAssignment extends DeclarationStatement { isExportEquals?: boolean; expression: Expression; } @@ -908,7 +993,7 @@ declare namespace ts { interface JSDocThisType extends JSDocType { type: JSDocType; } - interface JSDocRecordMember extends PropertyDeclaration { + interface JSDocRecordMember extends PropertySignature { name: Identifier | LiteralExpression; type?: JSDocType; } @@ -934,16 +1019,17 @@ declare namespace ts { postParameterName?: Identifier; isBracketed: boolean; } + interface AmdDependency { + path: string; + name: string; + } interface SourceFile extends Declaration { statements: NodeArray; endOfFileToken: Node; fileName: string; path: Path; text: string; - amdDependencies: { - path: string; - name: string; - }[]; + amdDependencies: AmdDependency[]; moduleName: string; referencedFiles: FileReference[]; languageVariant: LanguageVariant; @@ -1053,6 +1139,7 @@ declare namespace ts { getReturnTypeOfSignature(signature: Signature): Type; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol; + getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; getShorthandAssignmentValueSymbol(location: Node): Symbol; getTypeAtLocation(node: Node): Type; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; @@ -1078,7 +1165,7 @@ declare namespace ts { interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; @@ -1117,10 +1204,20 @@ declare namespace ts { WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, } + enum TypePredicateKind { + This = 0, + Identifier = 1, + } interface TypePredicate { + kind: TypePredicateKind; + type: Type; + } + interface ThisTypePredicate extends TypePredicate { + _thisTypePredicateBrand: any; + } + interface IdentifierTypePredicate extends TypePredicate { parameterName: string; parameterIndex: number; - type: Type; } enum SymbolFlags { None = 0, @@ -1222,6 +1319,7 @@ declare namespace ts { ESSymbol = 16777216, ThisType = 33554432, ObjectLiteralPatternWithComputedProperties = 67108864, + PredicateType = 134217728, StringLike = 258, NumberLike = 132, ObjectType = 80896, @@ -1234,6 +1332,9 @@ declare namespace ts { symbol?: Symbol; pattern?: DestructuringPattern; } + interface PredicateType extends Type { + predicate: ThisTypePredicate | IdentifierTypePredicate; + } interface StringLiteralType extends Type { text: string; } @@ -1279,7 +1380,6 @@ declare namespace ts { declaration: SignatureDeclaration; typeParameters: TypeParameter[]; parameters: Symbol[]; - typePredicate?: TypePredicate; } enum IndexKind { String = 0, @@ -1331,6 +1431,7 @@ declare namespace ts { inlineSourceMap?: boolean; inlineSources?: boolean; jsx?: JsxEmit; + reactNamespace?: string; listFiles?: boolean; locale?: string; mapRoot?: string; @@ -1366,6 +1467,8 @@ declare namespace ts { noImplicitReturns?: boolean; noFallthroughCasesInSwitch?: boolean; forceConsistentCasingInFileNames?: boolean; + allowSyntheticDefaultImports?: boolean; + allowJs?: boolean; [option: string]: string | number | boolean; } enum ModuleKind { @@ -1409,6 +1512,7 @@ declare namespace ts { interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string; + directoryExists?(directoryName: string): boolean; } interface ResolvedModule { resolvedFileName: string; @@ -1537,6 +1641,7 @@ declare namespace ts { */ function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; + function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -1546,10 +1651,10 @@ declare namespace ts { } declare namespace ts { const version: string; - function findConfigFile(searchPath: string): string; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1582,7 +1687,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -1590,7 +1695,7 @@ declare namespace ts { } declare namespace ts { /** The version of the language service API */ - let servicesVersion: string; + const servicesVersion: string; interface Node { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; @@ -1659,7 +1764,7 @@ declare namespace ts { /** Releases all resources held by this script snapshot */ dispose?(): void; } - module ScriptSnapshot { + namespace ScriptSnapshot { function fromString(text: string): IScriptSnapshot; } interface PreProcessedFileInfo { @@ -1687,6 +1792,7 @@ declare namespace ts { error?(s: string): void; useCaseSensitiveFileNames?(): boolean; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + directoryExists?(directoryName: string): boolean; } interface LanguageService { cleanupSemanticCache(): void; @@ -1782,7 +1888,7 @@ declare namespace ts { fileName: string; highlightSpans: HighlightSpan[]; } - module HighlightSpanKind { + namespace HighlightSpanKind { const none: string; const definition: string; const reference: string; @@ -1824,6 +1930,7 @@ declare namespace ts { InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; [s: string]: boolean | number | string; @@ -2068,7 +2175,7 @@ declare namespace ts { releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; reportStats(): string; } - module ScriptElementKind { + namespace ScriptElementKind { const unknown: string; const warning: string; const keyword: string; @@ -2099,7 +2206,7 @@ declare namespace ts { const constElement: string; const letElement: string; } - module ScriptElementKindModifier { + namespace ScriptElementKindModifier { const none: string; const publicMemberModifier: string; const privateMemberModifier: string; diff --git a/lib/typescript.js b/lib/typescript.js index 498ddc37860..1e2f51f5aae 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -195,133 +195,135 @@ var ts; SyntaxKind[SyntaxKind["UnionType"] = 158] = "UnionType"; SyntaxKind[SyntaxKind["IntersectionType"] = 159] = "IntersectionType"; SyntaxKind[SyntaxKind["ParenthesizedType"] = 160] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 161] = "ThisType"; + SyntaxKind[SyntaxKind["StringLiteralType"] = 162] = "StringLiteralType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 161] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 162] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 163] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 163] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 164] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 165] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 164] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 165] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 166] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 167] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 168] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 169] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 170] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 171] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 172] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 173] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 174] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 175] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 176] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 177] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 178] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 179] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 180] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 181] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 182] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 183] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 184] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElementExpression"] = 185] = "SpreadElementExpression"; - SyntaxKind[SyntaxKind["ClassExpression"] = 186] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 187] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 188] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 189] = "AsExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 166] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 167] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 168] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 169] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 170] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 171] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 172] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 173] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 174] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 175] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 176] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 177] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 178] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 179] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 180] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 181] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 182] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 183] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 184] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 185] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 186] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElementExpression"] = 187] = "SpreadElementExpression"; + SyntaxKind[SyntaxKind["ClassExpression"] = 188] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 189] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 190] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 191] = "AsExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 190] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 191] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 192] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 193] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 192] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 193] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 194] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 195] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 196] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 197] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 198] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 199] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 200] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 201] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 202] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 203] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 204] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 205] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 206] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 207] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 208] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 209] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 210] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 211] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 212] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 213] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 214] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 215] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 216] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 217] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 218] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 219] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 220] = "CaseBlock"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 221] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 222] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 223] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 224] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 225] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 226] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 227] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 228] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 229] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 230] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 231] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 194] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 195] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 196] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 197] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 198] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 199] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 200] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 201] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 202] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 203] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 204] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 205] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 206] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 207] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 208] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 209] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 210] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 211] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 212] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 213] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 214] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 215] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 216] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 217] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 218] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 219] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 220] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 221] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 222] = "CaseBlock"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 223] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 224] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 225] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 226] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 227] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 228] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 229] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 230] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 231] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 232] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 233] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 232] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 234] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 233] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 234] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 235] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxText"] = 236] = "JsxText"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 237] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 238] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 239] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 240] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 235] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 236] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 237] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxText"] = 238] = "JsxText"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 239] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 240] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 241] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 242] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 241] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 242] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 243] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 244] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 243] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 244] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 245] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 246] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 245] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 246] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 247] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 248] = "ShorthandPropertyAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 247] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 249] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 248] = "SourceFile"; + SyntaxKind[SyntaxKind["SourceFile"] = 250] = "SourceFile"; // JSDoc nodes. - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 249] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 251] = "JSDocTypeExpression"; // The * type. - SyntaxKind[SyntaxKind["JSDocAllType"] = 250] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 252] = "JSDocAllType"; // The ? type. - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 251] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocArrayType"] = 252] = "JSDocArrayType"; - SyntaxKind[SyntaxKind["JSDocUnionType"] = 253] = "JSDocUnionType"; - SyntaxKind[SyntaxKind["JSDocTupleType"] = 254] = "JSDocTupleType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 255] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 256] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocRecordType"] = 257] = "JSDocRecordType"; - SyntaxKind[SyntaxKind["JSDocRecordMember"] = 258] = "JSDocRecordMember"; - SyntaxKind[SyntaxKind["JSDocTypeReference"] = 259] = "JSDocTypeReference"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 260] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 261] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 262] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocConstructorType"] = 263] = "JSDocConstructorType"; - SyntaxKind[SyntaxKind["JSDocThisType"] = 264] = "JSDocThisType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 265] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 266] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 267] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 268] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 269] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 270] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 253] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 254] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 255] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 256] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 257] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 258] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 259] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 260] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 261] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 262] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 263] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 264] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 265] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 266] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 267] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 268] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 269] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 270] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 271] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 272] = "JSDocTemplateTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 271] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 273] = "SyntaxList"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 272] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 274] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; @@ -331,8 +333,8 @@ var ts; SyntaxKind[SyntaxKind["LastKeyword"] = 134] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 106] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 114] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 151] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 160] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 150] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 162] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 15] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 68] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; @@ -408,10 +410,14 @@ var ts; var ParserContextFlags = ts.ParserContextFlags; (function (JsxFlags) { JsxFlags[JsxFlags["None"] = 0] = "None"; + /** An element from a named property of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; - JsxFlags[JsxFlags["ClassElement"] = 4] = "ClassElement"; - JsxFlags[JsxFlags["UnknownElement"] = 8] = "UnknownElement"; + /** An element backed by a class, class-like, or function value */ + JsxFlags[JsxFlags["ValueElement"] = 4] = "ValueElement"; + /** Element resolution failed */ + JsxFlags[JsxFlags["UnknownElement"] = 16] = "UnknownElement"; JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; })(ts.JsxFlags || (ts.JsxFlags = {})); var JsxFlags = ts.JsxFlags; @@ -426,7 +432,7 @@ var ts; function OperationCanceledException() { } return OperationCanceledException; - })(); + }()); ts.OperationCanceledException = OperationCanceledException; /** Return code used by getEmitOutput function to indicate status of the function */ (function (ExitStatus) { @@ -472,6 +478,11 @@ var ts; SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; })(ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); var SymbolAccessibility = ts.SymbolAccessibility; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(ts.TypePredicateKind || (ts.TypePredicateKind = {})); + var TypePredicateKind = ts.TypePredicateKind; /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator * metadata */ /* @internal */ @@ -623,6 +634,7 @@ var ts; TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol"; TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType"; TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 67108864] = "ObjectLiteralPatternWithComputedProperties"; + TypeFlags[TypeFlags["PredicateType"] = 134217728] = "PredicateType"; /* @internal */ TypeFlags[TypeFlags["Intrinsic"] = 16777343] = "Intrinsic"; /* @internal */ @@ -633,7 +645,7 @@ var ts; TypeFlags[TypeFlags["UnionOrIntersection"] = 49152] = "UnionOrIntersection"; TypeFlags[TypeFlags["StructuredType"] = 130048] = "StructuredType"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 140509184] = "RequiresWidening"; /* @internal */ TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; })(ts.TypeFlags || (ts.TypeFlags = {})); @@ -648,6 +660,19 @@ var ts; IndexKind[IndexKind["Number"] = 1] = "Number"; })(ts.IndexKind || (ts.IndexKind = {})); var IndexKind = ts.IndexKind; + /* @internal */ + (function (SpecialPropertyAssignmentKind) { + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + /// exports.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + /// module.exports = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + /// className.prototype.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + /// this.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + })(ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + var SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; @@ -1068,9 +1093,11 @@ var ts; var count = array.length; if (count > 0) { var pos = 0; - var result = arguments.length <= 2 ? array[pos++] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos++; while (pos < count) { - result = f(result, array[pos++]); + result = f(result, array[pos]); + pos++; } return result; } @@ -1082,9 +1109,11 @@ var ts; if (array) { var pos = array.length - 1; if (pos >= 0) { - var result = arguments.length <= 2 ? array[pos--] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos--; while (pos >= 0) { - result = f(result, array[pos--]); + result = f(result, array[pos]); + pos--; } return result; } @@ -1177,6 +1206,32 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + /** + * Reduce the properties of a map. + * + * @param map The map to reduce + * @param callback An aggregation function that is called for each entry in the map + * @param initial The initial value for the reduction. + */ + 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; + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; function memoize(callback) { var value; return function () { @@ -1502,7 +1557,7 @@ var ts; } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; function getBaseFileName(path) { - if (!path) { + if (path === undefined) { return undefined; } var i = path.lastIndexOf(ts.directorySeparator); @@ -1530,14 +1585,19 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedJsExtensions = ts.supportedExtensions.concat(".js", ".jsx"); - function isSupportedSourceFileName(fileName) { + ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedJavascriptExtensions = [".js", ".jsx"]; + var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + function getSupportedExtensions(options) { + return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + ts.getSupportedExtensions = getSupportedExtensions; + function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; } - for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; + for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -1556,22 +1616,6 @@ var ts; return path; } ts.removeFileExtension = removeFileExtension; - var backslashOrDoubleQuote = /[\"\\]/g; - var escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { - "\0": "\\0", - "\t": "\\t", - "\v": "\\v", - "\f": "\\f", - "\b": "\\b", - "\r": "\\r", - "\n": "\\n", - "\\": "\\\\", - "\"": "\\\"", - "\u2028": "\\u2028", - "\u2029": "\\u2029", - "\u0085": "\\u0085" // nextLine - }; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -1622,7 +1666,7 @@ var ts; } Debug.assert = assert; function fail(message) { - Debug.assert(false, message); + Debug.assert(/*expression*/ false, message); } Debug.fail = fail; })(Debug = ts.Debug || (ts.Debug = {})); @@ -1783,7 +1827,6 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); - var _tty = require("tty"); // average async stat takes about 30 microseconds // set chunk size to do 30 files in < 1 millisecond function createWatchedFileSet(interval, chunkSize) { @@ -1858,7 +1901,7 @@ var ts; // REVIEW: for now this implementation uses polling. // The advantage of polling is that it works reliably // on all os and with network mounted files. - // For 90 referenced files, the average time to detect + // For 90 referenced files, the average time to detect // changes is 2*msInterval (by default 5 seconds). // The overhead of this is .04 percent (1/2500) with // average pause of < 1 millisecond (and max @@ -1869,9 +1912,6 @@ var ts; // to increase the chunk size or decrease the interval // time dynamically to match the large reference set? var watchedFileSet = createWatchedFileSet(); - function isNode4OrLater() { - return parseInt(process.version.charAt(1)) >= 4; - } var platform = _os.platform(); // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; @@ -1965,17 +2005,13 @@ var ts; // and is more efficient than `fs.watchFile` (ref: https://github.com/nodejs/node/pull/2649 // and https://github.com/Microsoft/TypeScript/issues/4643), therefore // if the current node.js version is newer than 4, use `fs.watch` instead. - if (isNode4OrLater()) { - // Note: in node the callback of fs.watch is given only the relative file name as a parameter - return _fs.watch(fileName, function (eventName, relativeFileName) { return callback(fileName); }); - } var watchedFile = watchedFileSet.addFile(fileName, callback); return { close: function () { return watchedFileSet.removeFile(watchedFile); } }; }, watchDirectory: function (path, callback, recursive) { - // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) return _fs.watch(path, { persistent: true, recursive: !!recursive }, function (eventName, relativeFileName) { // In watchDirectory we only care about adding and removing files (when event name is @@ -2020,6 +2056,33 @@ var ts; } }; } + function getChakraSystem() { + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, encoding) { + // encoding is automatically handled by the implementation in ChakraHost + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = "\uFEFF" + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + readDirectory: ChakraHost.readDirectory, + exit: ChakraHost.quit + }; + } if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { return getWScriptSystem(); } @@ -2028,6 +2091,9 @@ var ts; // process.browser check excludes webpack and browserify return getNodeSystem(); } + else if (typeof ChakraHost !== "undefined") { + return getChakraSystem(); + } else { return undefined; // Unsupported host } @@ -2148,7 +2214,7 @@ var ts; Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: ts.DiagnosticCategory.Error, key: "Modifiers_not_permitted_on_index_signature_members_1145", message: "Modifiers not permitted on index signature members." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_1148", message: "Cannot compile modules unless the '--module' flag is provided." }, + Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_optio_1148", message: "Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -2235,6 +2301,10 @@ var ts; _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, + An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, + A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, + A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, @@ -2248,11 +2318,12 @@ var ts; Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list_2313", message: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." }, + Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, @@ -2262,6 +2333,7 @@ var ts; Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, + Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, @@ -2332,6 +2404,7 @@ var ts; Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, + Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, @@ -2445,6 +2518,8 @@ var ts; Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, + A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_return_type_positions_for_functions_and_methods: { code: 2519, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_r_2519", message: "A 'this'-based type predicate is only allowed within a class or interface's members, get accessors, or return type positions for functions and methods." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, @@ -2454,7 +2529,7 @@ var ts; A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_must_be_an_object_type_2600", message: "JSX element attributes type '{0}' must be an object type." }, + 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." }, Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'" }, @@ -2470,6 +2545,9 @@ var ts; Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element" }, + Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'" }, + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, 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}'." }, @@ -2554,6 +2632,11 @@ var ts; Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, + Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'" }, + The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'" }, + Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalide value for '--reactNamespace'. '{0}' is not a valid identifier." }, 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." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -2564,6 +2647,7 @@ var ts; Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -2619,6 +2703,8 @@ var ts; Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, + Allow_javascript_files_to_be_compiled: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6083", message: "Allow javascript files to be compiled." }, + Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit_6084", message: "Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit" }, 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." }, @@ -2666,7 +2752,8 @@ var ts; Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'" }, An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." } + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, + JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." } }; })(ts || (ts = {})); /// @@ -2906,7 +2993,8 @@ var ts; var pos = 0; var lineStart = 0; while (pos < text.length) { - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 13 /* carriageReturn */: if (text.charCodeAt(pos) === 10 /* lineFeed */) { @@ -3040,6 +3128,11 @@ var ts; ts.couldStartTrivia = couldStartTrivia; /* @internal */ function skipTrivia(text, pos, stopAfterLineBreak) { + // Using ! with a greater than test is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + if (!(pos >= 0)) { + return pos; + } // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -3276,6 +3369,19 @@ var ts; ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; + /* @internal */ + function isIdentifier(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1, n = name.length; i < n; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifier = isIdentifier; // Creates a scanner over a (possibly unspecified) range of a piece of text. function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } @@ -3398,7 +3504,8 @@ var ts; return value; } function scanString() { - var quote = text.charCodeAt(pos++); + var quote = text.charCodeAt(pos); + pos++; var result = ""; var start = pos; while (true) { @@ -3494,7 +3601,8 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); return ""; } - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 48 /* _0 */: return "\0"; @@ -3721,7 +3829,8 @@ var ts; } return pos += 2, token = 31 /* ExclamationEqualsToken */; } - return pos++, token = 49 /* ExclamationToken */; + pos++; + return token = 49 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); @@ -3732,7 +3841,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 62 /* PercentEqualsToken */; } - return pos++, token = 40 /* PercentToken */; + pos++; + return token = 40 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { return pos += 2, token = 51 /* AmpersandAmpersandToken */; @@ -3740,11 +3850,14 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 66 /* AmpersandEqualsToken */; } - return pos++, token = 46 /* AmpersandToken */; + pos++; + return token = 46 /* AmpersandToken */; case 40 /* openParen */: - return pos++, token = 17 /* OpenParenToken */; + pos++; + return token = 17 /* OpenParenToken */; case 41 /* closeParen */: - return pos++, token = 18 /* CloseParenToken */; + pos++; + return token = 18 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 59 /* AsteriskEqualsToken */; @@ -3755,7 +3868,8 @@ var ts; } return pos += 2, token = 38 /* AsteriskAsteriskToken */; } - return pos++, token = 37 /* AsteriskToken */; + pos++; + return token = 37 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { return pos += 2, token = 41 /* PlusPlusToken */; @@ -3763,9 +3877,11 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 57 /* PlusEqualsToken */; } - return pos++, token = 35 /* PlusToken */; + pos++; + return token = 35 /* PlusToken */; case 44 /* comma */: - return pos++, token = 24 /* CommaToken */; + pos++; + return token = 24 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { return pos += 2, token = 42 /* MinusMinusToken */; @@ -3773,7 +3889,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 58 /* MinusEqualsToken */; } - return pos++, token = 36 /* MinusToken */; + pos++; + return token = 36 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { tokenValue = scanNumber(); @@ -3782,7 +3899,8 @@ var ts; if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { return pos += 3, token = 22 /* DotDotDotToken */; } - return pos++, token = 21 /* DotToken */; + pos++; + return token = 21 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -3830,7 +3948,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 61 /* SlashEqualsToken */; } - return pos++, token = 39 /* SlashToken */; + pos++; + return token = 39 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; @@ -3882,9 +4001,11 @@ var ts; tokenValue = scanNumber(); return token = 8 /* NumericLiteral */; case 58 /* colon */: - return pos++, token = 54 /* ColonToken */; + pos++; + return token = 54 /* ColonToken */; case 59 /* semicolon */: - return pos++, token = 23 /* SemicolonToken */; + pos++; + return token = 23 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3909,7 +4030,8 @@ var ts; text.charCodeAt(pos + 2) !== 42 /* asterisk */) { return pos += 2, token = 26 /* LessThanSlashToken */; } - return pos++, token = 25 /* LessThanToken */; + pos++; + return token = 25 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3929,7 +4051,8 @@ var ts; if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { return pos += 2, token = 34 /* EqualsGreaterThanToken */; } - return pos++, token = 56 /* EqualsToken */; + pos++; + return token = 56 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3940,20 +4063,26 @@ var ts; return token = 7 /* ConflictMarkerTrivia */; } } - return pos++, token = 27 /* GreaterThanToken */; + pos++; + return token = 27 /* GreaterThanToken */; case 63 /* question */: - return pos++, token = 53 /* QuestionToken */; + pos++; + return token = 53 /* QuestionToken */; case 91 /* openBracket */: - return pos++, token = 19 /* OpenBracketToken */; + pos++; + return token = 19 /* OpenBracketToken */; case 93 /* closeBracket */: - return pos++, token = 20 /* CloseBracketToken */; + pos++; + return token = 20 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 68 /* CaretEqualsToken */; } - return pos++, token = 48 /* CaretToken */; + pos++; + return token = 48 /* CaretToken */; case 123 /* openBrace */: - return pos++, token = 15 /* OpenBraceToken */; + pos++; + return token = 15 /* OpenBraceToken */; case 124 /* bar */: if (text.charCodeAt(pos + 1) === 124 /* bar */) { return pos += 2, token = 52 /* BarBarToken */; @@ -3961,13 +4090,17 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 67 /* BarEqualsToken */; } - return pos++, token = 47 /* BarToken */; + pos++; + return token = 47 /* BarToken */; case 125 /* closeBrace */: - return pos++, token = 16 /* CloseBraceToken */; + pos++; + return token = 16 /* CloseBraceToken */; case 126 /* tilde */: - return pos++, token = 50 /* TildeToken */; + pos++; + return token = 50 /* TildeToken */; case 64 /* at */: - return pos++, token = 55 /* AtToken */; + pos++; + return token = 55 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -3976,7 +4109,8 @@ var ts; return token = getIdentifierToken(); } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0 /* Unknown */; + pos++; + return token = 0 /* Unknown */; default: if (isIdentifierStart(ch, languageVersion)) { pos++; @@ -3998,7 +4132,8 @@ var ts; continue; } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0 /* Unknown */; + pos++; + return token = 0 /* Unknown */; } } } @@ -4014,10 +4149,12 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 64 /* GreaterThanGreaterThanEqualsToken */; } - return pos++, token = 44 /* GreaterThanGreaterThanToken */; + pos++; + return token = 44 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { - return pos++, token = 29 /* GreaterThanEqualsToken */; + pos++; + return token = 29 /* GreaterThanEqualsToken */; } } return token; @@ -4109,7 +4246,7 @@ var ts; break; } } - return token = 236 /* JsxText */; + return token = 238 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -4150,10 +4287,10 @@ var ts; return result; } function lookAhead(callback) { - return speculationHelper(callback, /*isLookahead:*/ true); + return speculationHelper(callback, /*isLookahead*/ true); } function tryScan(callback) { - return speculationHelper(callback, /*isLookahead:*/ false); + return speculationHelper(callback, /*isLookahead*/ false); } function setText(newText, start, length) { text = newText || ""; @@ -4244,7 +4381,7 @@ var ts; if (array1.length !== array2.length) { return false; } - for (var i = 0; i < array1.length; ++i) { + for (var i = 0; i < array1.length; i++) { var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; if (!equals) { return false; @@ -4292,7 +4429,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 248 /* SourceFile */) { + while (node && node.kind !== 250 /* SourceFile */) { node = node.parent; } return node; @@ -4404,15 +4541,15 @@ var ts; return current; } switch (current.kind) { - case 248 /* SourceFile */: - case 220 /* CaseBlock */: - case 244 /* CatchClause */: - case 218 /* ModuleDeclaration */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 250 /* SourceFile */: + case 222 /* CaseBlock */: + case 246 /* CatchClause */: + case 220 /* ModuleDeclaration */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: return current; - case 192 /* Block */: + case 194 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block if (!isFunctionLike(current.parent)) { @@ -4425,9 +4562,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 211 /* VariableDeclaration */ && + declaration.kind === 213 /* VariableDeclaration */ && declaration.parent && - declaration.parent.kind === 244 /* CatchClause */; + declaration.parent.kind === 246 /* CatchClause */; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; // Return display name of an identifier @@ -4466,7 +4603,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -4475,16 +4612,17 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 217 /* InterfaceDeclaration */: + case 220 /* ModuleDeclaration */: + case 219 /* EnumDeclaration */: + case 249 /* EnumMember */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 143 /* MethodDeclaration */: errorNode = node.name; break; } @@ -4512,11 +4650,11 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 217 /* EnumDeclaration */ && isConst(node); + return node.kind === 219 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 163 /* BindingElement */ || isBindingPattern(node))) { + while (node && (node.kind === 165 /* BindingElement */ || isBindingPattern(node))) { node = node.parent; } return node; @@ -4531,14 +4669,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 211 /* VariableDeclaration */) { + if (node.kind === 213 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 212 /* VariableDeclarationList */) { + if (node && node.kind === 214 /* VariableDeclarationList */) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 193 /* VariableStatement */) { + if (node && node.kind === 195 /* VariableStatement */) { flags |= node.flags; } return flags; @@ -4553,7 +4691,7 @@ var ts; } ts.isLet = isLet; function isPrologueDirective(node) { - return node.kind === 195 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; + return node.kind === 197 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { @@ -4584,7 +4722,7 @@ var ts; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isTypeNode(node) { - if (151 /* FirstTypeNode */ <= node.kind && node.kind <= 160 /* LastTypeNode */) { + if (150 /* FirstTypeNode */ <= node.kind && node.kind <= 162 /* LastTypeNode */) { return true; } switch (node.kind) { @@ -4595,11 +4733,8 @@ var ts; case 131 /* SymbolKeyword */: return true; case 103 /* VoidKeyword */: - return node.parent.kind !== 177 /* VoidExpression */; - case 9 /* StringLiteral */: - // Specialized signatures can have string literals as their parameters' type names - return node.parent.kind === 138 /* Parameter */; - case 188 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 179 /* VoidExpression */; + case 190 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container @@ -4608,13 +4743,13 @@ var ts; if (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 168 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 168 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); case 135 /* QualifiedName */: - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: case 97 /* ThisKeyword */: var parent_1 = node.parent; if (parent_1.kind === 154 /* TypeQuery */) { @@ -4626,22 +4761,22 @@ var ts; // // Calling isTypeNode would consider the qualified name A.B a type node. Only C or // A.B.C is a type node. - if (151 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 160 /* LastTypeNode */) { + if (150 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 162 /* LastTypeNode */) { return true; } switch (parent_1.kind) { - case 188 /* ExpressionWithTypeArguments */: + case 190 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); case 137 /* TypeParameter */: return node === parent_1.constraint; case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 138 /* Parameter */: - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: return node === parent_1.type; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: case 144 /* Constructor */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: @@ -4652,12 +4787,12 @@ var ts; case 148 /* ConstructSignature */: case 149 /* IndexSignature */: return node === parent_1.type; - case 171 /* TypeAssertionExpression */: + case 173 /* TypeAssertionExpression */: return node === parent_1.type; - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 170 /* TaggedTemplateExpression */: + case 172 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -4671,23 +4806,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 204 /* ReturnStatement */: + case 206 /* ReturnStatement */: return visitor(node); - case 220 /* CaseBlock */: - case 192 /* Block */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: + case 222 /* CaseBlock */: + case 194 /* Block */: + case 198 /* IfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 207 /* WithStatement */: + case 208 /* SwitchStatement */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: + case 209 /* LabeledStatement */: + case 211 /* TryStatement */: + case 246 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -4697,18 +4832,18 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 184 /* YieldExpression */: + case 186 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 219 /* EnumDeclaration */: + case 217 /* InterfaceDeclaration */: + case 220 /* ModuleDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. @@ -4735,14 +4870,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 163 /* BindingElement */: - case 247 /* EnumMember */: + case 165 /* BindingElement */: + case 249 /* EnumMember */: case 138 /* Parameter */: - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 246 /* ShorthandPropertyAssignment */: - case 211 /* VariableDeclaration */: + case 248 /* ShorthandPropertyAssignment */: + case 213 /* VariableDeclaration */: return true; } } @@ -4754,7 +4889,7 @@ var ts; } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 214 /* ClassDeclaration */ || node.kind === 186 /* ClassExpression */); + return node && (node.kind === 216 /* ClassDeclaration */ || node.kind === 188 /* ClassExpression */); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -4764,9 +4899,9 @@ var ts; function isFunctionLikeKind(kind) { switch (kind) { case 144 /* Constructor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 176 /* ArrowFunction */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: @@ -4787,8 +4922,8 @@ var ts; case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: return true; } return false; @@ -4796,26 +4931,30 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: return true; - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 192 /* Block */ && isFunctionLike(node.parent); + return node && node.kind === 194 /* Block */ && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 143 /* MethodDeclaration */ && node.parent.kind === 165 /* ObjectLiteralExpression */; + return node && node.kind === 143 /* MethodDeclaration */ && node.parent.kind === 167 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1 /* Identifier */; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; function getContainingFunction(node) { while (true) { node = node.parent; @@ -4869,14 +5008,14 @@ var ts; node = node.parent; } break; - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // Fall through - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 218 /* ModuleDeclaration */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 220 /* ModuleDeclaration */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 143 /* MethodDeclaration */: @@ -4887,34 +5026,45 @@ var ts; case 147 /* CallSignature */: case 148 /* ConstructSignature */: case 149 /* IndexSignature */: - case 217 /* EnumDeclaration */: - case 248 /* SourceFile */: + case 219 /* EnumDeclaration */: + case 250 /* SourceFile */: return node; } } } ts.getThisContainer = getThisContainer; - function getSuperContainer(node, includeFunctions) { + /** + * Given an super call\property node returns a closest node where either + * - super call\property is legal in the node and not legal in the parent node the node. + * i.e. super call is legal in constructor but not legal in the class body. + * - node is arrow function (so caller might need to call getSuperContainer in case if he needs to climb higher) + * - super call\property is definitely illegal in the node (but might be legal in some subnode) + * i.e. super property access is illegal in function declaration but can be legal in the statement list + */ + function getSuperContainer(node, stopOnFunctions) { while (true) { node = node.parent; - if (!node) + if (!node) { return node; + } switch (node.kind) { case 136 /* ComputedPropertyName */: - // If the grandparent node is an object literal (as opposed to a class), - // then the computed property is not a 'super' container. - // A computed property name in a class needs to be a super container - // so that we can error on it. - if (isClassLike(node.parent.parent)) { - return node; - } - // If this is a computed property, then the parent should not - // make it a super container. The parent might be a property - // in an object literal, like a method or accessor. But in order for - // such a parent to be a super container, the reference must be in - // the *body* of the container. node = node.parent; break; + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + if (!stopOnFunctions) { + continue; + } + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + return node; case 139 /* Decorator */: // Decorators are always applied outside of the body of a class or method. if (node.parent.kind === 138 /* Parameter */ && isClassElement(node.parent.parent)) { @@ -4928,20 +5078,6 @@ var ts; node = node.parent; } break; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - if (!includeFunctions) { - continue; - } - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - return node; } } } @@ -4951,7 +5087,7 @@ var ts; switch (node.kind) { case 151 /* TypeReference */: return node.typeName; - case 188 /* ExpressionWithTypeArguments */: + case 190 /* ExpressionWithTypeArguments */: return node.expression; case 69 /* Identifier */: case 135 /* QualifiedName */: @@ -4962,7 +5098,7 @@ var ts; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 172 /* TaggedTemplateExpression */) { return node.tag; } // Will either be a CallExpression, NewExpression, or Decorator. @@ -4971,27 +5107,27 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: // classes are valid targets return true; case 141 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return node.parent.kind === 214 /* ClassDeclaration */; + return node.parent.kind === 216 /* ClassDeclaration */; case 138 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; - return node.parent.body && node.parent.parent.kind === 214 /* ClassDeclaration */; + return node.parent.body && node.parent.parent.kind === 216 /* ClassDeclaration */; case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 143 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. - return node.body && node.parent.kind === 214 /* ClassDeclaration */; + return node.body && node.parent.kind === 216 /* ClassDeclaration */; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { switch (node.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: if (node.decorators) { return true; } @@ -5017,27 +5153,12 @@ var ts; return false; } ts.nodeIsDecorated = nodeIsDecorated; - function childIsDecorated(node) { - switch (node.kind) { - case 214 /* ClassDeclaration */: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 143 /* MethodDeclaration */: - case 146 /* SetAccessor */: - return ts.forEach(node.parameters, nodeIsDecorated); - } - return false; - } - ts.childIsDecorated = childIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); - } - ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function isPropertyAccessExpression(node) { - return node.kind === 166 /* PropertyAccessExpression */; + return node.kind === 168 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 167 /* ElementAccessExpression */; + return node.kind === 169 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isExpression(node) { @@ -5047,34 +5168,34 @@ var ts; case 99 /* TrueKeyword */: case 84 /* FalseKeyword */: case 10 /* RegularExpressionLiteral */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 170 /* TaggedTemplateExpression */: - case 189 /* AsExpression */: - case 171 /* TypeAssertionExpression */: - case 172 /* ParenthesizedExpression */: - case 173 /* FunctionExpression */: - case 186 /* ClassExpression */: - case 174 /* ArrowFunction */: - case 177 /* VoidExpression */: - case 175 /* DeleteExpression */: - case 176 /* TypeOfExpression */: - case 179 /* PrefixUnaryExpression */: - case 180 /* PostfixUnaryExpression */: - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 183 /* TemplateExpression */: + case 166 /* ArrayLiteralExpression */: + case 167 /* ObjectLiteralExpression */: + case 168 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: + case 172 /* TaggedTemplateExpression */: + case 191 /* AsExpression */: + case 173 /* TypeAssertionExpression */: + case 174 /* ParenthesizedExpression */: + case 175 /* FunctionExpression */: + case 188 /* ClassExpression */: + case 176 /* ArrowFunction */: + case 179 /* VoidExpression */: + case 177 /* DeleteExpression */: + case 178 /* TypeOfExpression */: + case 181 /* PrefixUnaryExpression */: + case 182 /* PostfixUnaryExpression */: + case 183 /* BinaryExpression */: + case 184 /* ConditionalExpression */: + case 187 /* SpreadElementExpression */: + case 185 /* TemplateExpression */: case 11 /* NoSubstitutionTemplateLiteral */: - case 187 /* OmittedExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 184 /* YieldExpression */: - case 178 /* AwaitExpression */: + case 189 /* OmittedExpression */: + case 235 /* JsxElement */: + case 236 /* JsxSelfClosingElement */: + case 186 /* YieldExpression */: + case 180 /* AwaitExpression */: return true; case 135 /* QualifiedName */: while (node.parent.kind === 135 /* QualifiedName */) { @@ -5091,47 +5212,47 @@ var ts; case 97 /* ThisKeyword */: var parent_2 = node.parent; switch (parent_2.kind) { - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: case 138 /* Parameter */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 247 /* EnumMember */: - case 245 /* PropertyAssignment */: - case 163 /* BindingElement */: + case 249 /* EnumMember */: + case 247 /* PropertyAssignment */: + case 165 /* BindingElement */: return parent_2.initializer === node; - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 204 /* ReturnStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 208 /* ThrowStatement */: - case 206 /* SwitchStatement */: + case 197 /* ExpressionStatement */: + case 198 /* IfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: + case 206 /* ReturnStatement */: + case 207 /* WithStatement */: + case 208 /* SwitchStatement */: + case 243 /* CaseClause */: + case 210 /* ThrowStatement */: + case 208 /* SwitchStatement */: return parent_2.expression === node; - case 199 /* ForStatement */: + case 201 /* ForStatement */: var forStatement = parent_2; - return (forStatement.initializer === node && forStatement.initializer.kind !== 212 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 214 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: var forInStatement = parent_2; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 212 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 214 /* VariableDeclarationList */) || forInStatement.expression === node; - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 173 /* TypeAssertionExpression */: + case 191 /* AsExpression */: return node === parent_2.expression; - case 190 /* TemplateSpan */: + case 192 /* TemplateSpan */: return node === parent_2.expression; case 136 /* ComputedPropertyName */: return node === parent_2.expression; case 139 /* Decorator */: - case 240 /* JsxExpression */: - case 239 /* JsxSpreadAttribute */: + case 242 /* JsxExpression */: + case 241 /* JsxSpreadAttribute */: return true; - case 188 /* ExpressionWithTypeArguments */: + case 190 /* ExpressionWithTypeArguments */: return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: if (isExpression(parent_2)) { @@ -5155,7 +5276,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 232 /* ExternalModuleReference */; + return node.kind === 223 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 234 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -5164,7 +5285,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 232 /* ExternalModuleReference */; + return node.kind === 223 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 234 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -5182,53 +5303,59 @@ var ts; */ function isRequireCall(expression) { // of the form 'require("name")' - return expression.kind === 168 /* CallExpression */ && + return expression.kind === 170 /* CallExpression */ && expression.expression.kind === 69 /* Identifier */ && expression.expression.text === "require" && expression.arguments.length === 1 && expression.arguments[0].kind === 9 /* StringLiteral */; } ts.isRequireCall = isRequireCall; - /** - * Returns true if the node is an assignment to a property on the identifier 'exports'. - * This function does not test if the node is in a JavaScript file or not. - */ - function isExportsPropertyAssignment(expression) { - // of the form 'exports.name = expr' where 'name' and 'expr' are arbitrary - return isInJavaScriptFile(expression) && - (expression.kind === 181 /* BinaryExpression */) && - (expression.operatorToken.kind === 56 /* EqualsToken */) && - (expression.left.kind === 166 /* PropertyAccessExpression */) && - (expression.left.expression.kind === 69 /* Identifier */) && - ((expression.left.expression).text === "exports"); + /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property + /// assignments we treat as special in the binder + function getSpecialPropertyAssignmentKind(expression) { + if (expression.kind !== 183 /* BinaryExpression */) { + return 0 /* None */; + } + var expr = expression; + if (expr.operatorToken.kind !== 56 /* EqualsToken */ || expr.left.kind !== 168 /* PropertyAccessExpression */) { + return 0 /* None */; + } + var lhs = expr.left; + if (lhs.expression.kind === 69 /* Identifier */) { + var lhsId = lhs.expression; + if (lhsId.text === "exports") { + // exports.name = expr + return 1 /* ExportsProperty */; + } + else if (lhsId.text === "module" && lhs.name.text === "exports") { + // module.exports = expr + return 2 /* ModuleExports */; + } + } + else if (lhs.expression.kind === 97 /* ThisKeyword */) { + return 4 /* ThisProperty */; + } + else if (lhs.expression.kind === 168 /* PropertyAccessExpression */) { + // chained dot, e.g. x.y.z = expr; this var is the 'x.y' part + var innerPropertyAccess = lhs.expression; + if (innerPropertyAccess.expression.kind === 69 /* Identifier */ && innerPropertyAccess.name.text === "prototype") { + return 3 /* PrototypeProperty */; + } + } + return 0 /* None */; } - ts.isExportsPropertyAssignment = isExportsPropertyAssignment; - /** - * Returns true if the node is an assignment to the property access expression 'module.exports'. - * This function does not test if the node is in a JavaScript file or not. - */ - function isModuleExportsAssignment(expression) { - // of the form 'module.exports = expr' where 'expr' is arbitrary - return isInJavaScriptFile(expression) && - (expression.kind === 181 /* BinaryExpression */) && - (expression.operatorToken.kind === 56 /* EqualsToken */) && - (expression.left.kind === 166 /* PropertyAccessExpression */) && - (expression.left.expression.kind === 69 /* Identifier */) && - ((expression.left.expression).text === "module") && - (expression.left.name.text === "exports"); - } - ts.isModuleExportsAssignment = isModuleExportsAssignment; + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 222 /* ImportDeclaration */) { + if (node.kind === 224 /* ImportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 223 /* ImportEqualsDeclaration */) { var reference = node.moduleReference; - if (reference.kind === 232 /* ExternalModuleReference */) { + if (reference.kind === 234 /* ExternalModuleReference */) { return reference.expression; } } - if (node.kind === 228 /* ExportDeclaration */) { + if (node.kind === 230 /* ExportDeclaration */) { return node.moduleSpecifier; } } @@ -5239,8 +5366,8 @@ var ts; case 138 /* Parameter */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - case 246 /* ShorthandPropertyAssignment */: - case 245 /* PropertyAssignment */: + case 248 /* ShorthandPropertyAssignment */: + case 247 /* PropertyAssignment */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return node.questionToken !== undefined; @@ -5250,9 +5377,9 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 261 /* JSDocFunctionType */ && + return node.kind === 263 /* JSDocFunctionType */ && node.parameters.length > 0 && - node.parameters[0].type.kind === 263 /* JSDocConstructorType */; + node.parameters[0].type.kind === 265 /* JSDocConstructorType */; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function getJSDocTag(node, kind) { @@ -5266,15 +5393,15 @@ var ts; } } function getJSDocTypeTag(node) { - return getJSDocTag(node, 269 /* JSDocTypeTag */); + return getJSDocTag(node, 271 /* JSDocTypeTag */); } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 268 /* JSDocReturnTag */); + return getJSDocTag(node, 270 /* JSDocReturnTag */); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 270 /* JSDocTemplateTag */); + return getJSDocTag(node, 272 /* JSDocTemplateTag */); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getCorrespondingJSDocParameterTag(parameter) { @@ -5285,7 +5412,7 @@ var ts; var docComment = parameter.parent.jsDocComment; if (docComment) { return ts.forEach(docComment.tags, function (t) { - if (t.kind === 267 /* JSDocParameterTag */) { + if (t.kind === 269 /* JSDocParameterTag */) { var parameterTag = t; var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; if (name_6.text === parameterName) { @@ -5304,12 +5431,12 @@ var ts; function isRestParameter(node) { if (node) { if (node.parserContextFlags & 32 /* JavaScriptFile */) { - if (node.type && node.type.kind === 262 /* JSDocVariadicType */) { + if (node.type && node.type.kind === 264 /* JSDocVariadicType */) { return true; } var paramTag = getCorrespondingJSDocParameterTag(node); if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 262 /* JSDocVariadicType */; + return paramTag.typeExpression.type.kind === 264 /* JSDocVariadicType */; } } return node.dotDotDotToken !== undefined; @@ -5330,7 +5457,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 162 /* ArrayBindingPattern */ || node.kind === 161 /* ObjectBindingPattern */); + return !!node && (node.kind === 164 /* ArrayBindingPattern */ || node.kind === 163 /* ObjectBindingPattern */); } ts.isBindingPattern = isBindingPattern; function isNodeDescendentOf(node, ancestor) { @@ -5354,34 +5481,34 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 174 /* ArrowFunction */: - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 176 /* ArrowFunction */: + case 165 /* BindingElement */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: case 144 /* Constructor */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 230 /* ExportSpecifier */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 219 /* EnumDeclaration */: + case 249 /* EnumMember */: + case 232 /* ExportSpecifier */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 145 /* GetAccessor */: - case 223 /* ImportClause */: - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 215 /* InterfaceDeclaration */: + case 225 /* ImportClause */: + case 223 /* ImportEqualsDeclaration */: + case 228 /* ImportSpecifier */: + case 217 /* InterfaceDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - case 218 /* ModuleDeclaration */: - case 224 /* NamespaceImport */: + case 220 /* ModuleDeclaration */: + case 226 /* NamespaceImport */: case 138 /* Parameter */: - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 146 /* SetAccessor */: - case 246 /* ShorthandPropertyAssignment */: - case 216 /* TypeAliasDeclaration */: + case 248 /* ShorthandPropertyAssignment */: + case 218 /* TypeAliasDeclaration */: case 137 /* TypeParameter */: - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: return true; } return false; @@ -5389,25 +5516,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: - case 210 /* DebuggerStatement */: - case 197 /* DoStatement */: - case 195 /* ExpressionStatement */: - case 194 /* EmptyStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 196 /* IfStatement */: - case 207 /* LabeledStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 193 /* VariableStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 227 /* ExportAssignment */: + case 205 /* BreakStatement */: + case 204 /* ContinueStatement */: + case 212 /* DebuggerStatement */: + case 199 /* DoStatement */: + case 197 /* ExpressionStatement */: + case 196 /* EmptyStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 201 /* ForStatement */: + case 198 /* IfStatement */: + case 209 /* LabeledStatement */: + case 206 /* ReturnStatement */: + case 208 /* SwitchStatement */: + case 210 /* ThrowStatement */: + case 211 /* TryStatement */: + case 195 /* VariableStatement */: + case 200 /* WhileStatement */: + case 207 /* WithStatement */: + case 229 /* ExportAssignment */: return true; default: return false; @@ -5435,7 +5562,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 226 /* ImportSpecifier */ || parent.kind === 230 /* ExportSpecifier */) { + if (parent.kind === 228 /* ImportSpecifier */ || parent.kind === 232 /* ExportSpecifier */) { if (parent.propertyName) { return true; } @@ -5456,9 +5583,9 @@ var ts; case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 247 /* EnumMember */: - case 245 /* PropertyAssignment */: - case 166 /* PropertyAccessExpression */: + case 249 /* EnumMember */: + case 247 /* PropertyAssignment */: + case 168 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; case 135 /* QualifiedName */: @@ -5470,11 +5597,11 @@ var ts; return parent.kind === 154 /* TypeQuery */; } return false; - case 163 /* BindingElement */: - case 226 /* ImportSpecifier */: + case 165 /* BindingElement */: + case 228 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 230 /* ExportSpecifier */: + case 232 /* ExportSpecifier */: // Any name in an export specifier return true; } @@ -5490,12 +5617,12 @@ var ts; // export = ... // export default ... function isAliasSymbolDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ || - node.kind === 223 /* ImportClause */ && !!node.name || - node.kind === 224 /* NamespaceImport */ || - node.kind === 226 /* ImportSpecifier */ || - node.kind === 230 /* ExportSpecifier */ || - node.kind === 227 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; + return node.kind === 223 /* ImportEqualsDeclaration */ || + node.kind === 225 /* ImportClause */ && !!node.name || + node.kind === 226 /* NamespaceImport */ || + node.kind === 228 /* ImportSpecifier */ || + node.kind === 232 /* ExportSpecifier */ || + node.kind === 229 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -5643,7 +5770,7 @@ var ts; return node.kind === 69 /* Identifier */ && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; - function isModifier(token) { + function isModifierKind(token) { switch (token) { case 115 /* AbstractKeyword */: case 118 /* AsyncKeyword */: @@ -5659,39 +5786,73 @@ var ts; } return false; } - ts.isModifier = isModifier; + ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); return root.kind === 138 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 163 /* BindingElement */) { + while (node.kind === 165 /* BindingElement */) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 218 /* ModuleDeclaration */ || n.kind === 248 /* SourceFile */; + return isFunctionLike(n) || n.kind === 220 /* ModuleDeclaration */ || n.kind === 250 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function cloneEntityName(node) { - if (node.kind === 69 /* Identifier */) { - var clone_1 = createSynthesizedNode(69 /* Identifier */); - clone_1.text = node.text; - return clone_1; + /** + * Creates a shallow, memberwise clone of a node. The "kind", "pos", "end", "flags", and "parent" + * properties are excluded by default, and can be provided via the "location", "flags", and + * "parent" parameters. + * @param node The node to clone. + * @param location An optional TextRange to use to supply the new position. + * @param flags The NodeFlags to use for the cloned node. + * @param parent The parent for the new node. + */ + function cloneNode(node, location, flags, parent) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + var clone = location !== undefined + ? ts.createNode(node.kind, location.pos, location.end) + : createSynthesizedNode(node.kind); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; } - else { - var clone_2 = createSynthesizedNode(135 /* QualifiedName */); - clone_2.left = cloneEntityName(node.left); - clone_2.left.parent = clone_2; - clone_2.right = cloneEntityName(node.right); - clone_2.right.parent = clone_2; - return clone_2; + if (flags !== undefined) { + clone.flags = flags; } + if (parent !== undefined) { + clone.parent = parent; + } + return clone; + } + ts.cloneNode = cloneNode; + /** + * Creates a deep clone of an EntityName, with new parent pointers. + * @param node The EntityName to clone. + * @param parent The parent for the cloned node. + */ + function cloneEntityName(node, parent) { + var clone = cloneNode(node, node, node.flags, parent); + if (isQualifiedName(clone)) { + var left = clone.left, right = clone.right; + clone.left = cloneEntityName(left, clone); + clone.right = cloneNode(right, right, right.flags, parent); + } + return clone; } ts.cloneEntityName = cloneEntityName; + function isQualifiedName(node) { + return node.kind === 135 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { return node.pos === -1; } @@ -5906,8 +6067,8 @@ var ts; writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, - increaseIndent: function () { return indent++; }, - decreaseIndent: function () { return indent--; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, getIndent: function () { return indent; }, getTextPos: function () { return output.length; }, getLine: function () { return lineCount + 1; }, @@ -5921,8 +6082,10 @@ var ts; * Resolves a local path to a path which is absolute to the base of the emit */ function getExternalModuleNameFromPath(host, fileName) { - var dir = host.getCurrentDirectory(); - var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, fileName, dir, function (f) { return host.getCanonicalFileName(f); }, /*isAbsolutePathAnUrl*/ false); + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); return ts.removeFileExtension(relativePath); } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; @@ -5938,6 +6101,63 @@ var ts; return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return compilerOptions.module ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { + var options = host.getCompilerOptions(); + // Emit on each source file + if (options.outFile || options.out) { + onBundledEmit(host); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + if (!isDeclarationFile(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, sourceFile.languageVariant === 1 /* JSX */ && options.jsx === 1 /* Preserve */ ? ".jsx" : ".js"); + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitFilePath(jsFilePath, options) : undefined + }; + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); + } + function onBundledEmit(host) { + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + (!isExternalModule(sourceFile) || + (getEmitModuleKind(options) && isExternalModule(sourceFile))); }); // module that can emit - note falsy value from getEmitModuleKind means the module kind that shouldn't be emitted + if (bundledSources.length) { + var jsFilePath = options.outFile || options.out; + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: getDeclarationEmitFilePath(jsFilePath, options) + }; + action(emitFileNames, bundledSources, /*isBundledEmit*/ true); + } + } + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getDeclarationEmitFilePath(jsFilePath, options) { + return options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + } + } + ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); @@ -5946,7 +6166,7 @@ var ts; ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { - diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); }); } ts.writeFile = writeFile; @@ -5970,18 +6190,6 @@ var ts; return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; - function shouldEmitToOwnFile(sourceFile, compilerOptions) { - if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !(compilerOptions.outFile || compilerOptions.out))) { - // 1. in-browser single file compilation scenario - // 2. non .js file - return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); - } - return false; - } - return false; - } - ts.shouldEmitToOwnFile = shouldEmitToOwnFile; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -6225,24 +6433,24 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 169 /* NewExpression */: - case 168 /* CallExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 170 /* TaggedTemplateExpression */: - case 164 /* ArrayLiteralExpression */: - case 172 /* ParenthesizedExpression */: - case 165 /* ObjectLiteralExpression */: - case 186 /* ClassExpression */: - case 173 /* FunctionExpression */: + case 168 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: + case 171 /* NewExpression */: + case 170 /* CallExpression */: + case 235 /* JsxElement */: + case 236 /* JsxSelfClosingElement */: + case 172 /* TaggedTemplateExpression */: + case 166 /* ArrayLiteralExpression */: + case 174 /* ParenthesizedExpression */: + case 167 /* ObjectLiteralExpression */: + case 188 /* ClassExpression */: + case 175 /* FunctionExpression */: case 69 /* Identifier */: case 10 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 11 /* NoSubstitutionTemplateLiteral */: - case 183 /* TemplateExpression */: + case 185 /* TemplateExpression */: case 84 /* FalseKeyword */: case 93 /* NullKeyword */: case 97 /* ThisKeyword */: @@ -6259,7 +6467,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 188 /* ExpressionWithTypeArguments */ && + return node.kind === 190 /* ExpressionWithTypeArguments */ && node.parent.token === 83 /* ExtendsKeyword */ && isClassLike(node.parent.parent); } @@ -6283,15 +6491,15 @@ var ts; } function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node); + (node.parent.kind === 168 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 165 /* ObjectLiteralExpression */) { + if (kind === 167 /* ObjectLiteralExpression */) { return expression.properties.length === 0; } - if (kind === 164 /* ArrayLiteralExpression */) { + if (kind === 166 /* ArrayLiteralExpression */) { return expression.elements.length === 0; } return false; @@ -6302,13 +6510,9 @@ var ts; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function hasJavaScriptFileExtension(fileName) { - return ts.fileExtensionIs(fileName, ".js") || ts.fileExtensionIs(fileName, ".jsx"); + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function allowsJsxExpressions(fileName) { - return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx"); - } - ts.allowsJsxExpressions = allowsJsxExpressions; /** * 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. @@ -6343,6 +6547,47 @@ var ts; } return output; } + /** + * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph + * as the fallback implementation does not check for circular references by default. + */ + ts.stringify = typeof JSON !== "undefined" && JSON.stringify + ? JSON.stringify + : stringifyFallback; + /** + * Serialize an object graph into a JSON string. + */ + function stringifyFallback(value) { + // JSON.stringify returns `undefined` here, instead of the string "undefined". + return value === undefined ? undefined : stringifyValue(value); + } + function stringifyValue(value) { + return typeof value === "string" ? "\"" + escapeString(value) + "\"" + : typeof value === "number" ? isFinite(value) ? String(value) : "null" + : typeof value === "boolean" ? value ? "true" : "false" + : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) + : "null"; + } + function cycleCheck(cb, value) { + ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); + value.__cycle = true; + var result = cb(value); + delete value.__cycle; + return result; + } + function stringifyArray(value) { + return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; + } + function stringifyElement(memo, value) { + return (memo ? memo + "," : memo) + stringifyValue(value); + } + function stringifyObject(value) { + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + } + function stringifyProperty(memo, value, key) { + return value === undefined || typeof value === "function" || key === "__cycle" ? memo + : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); + } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; /** * Converts a string to a base-64 encoded ASCII string. @@ -6611,13 +6856,17 @@ var ts; function getTypeParameterOwner(d) { if (d && d.kind === 137 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 215 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 217 /* InterfaceDeclaration */) { return current; } } } } ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return node.flags & 56 /* AccessibilityModifier */ && node.parent.kind === 144 /* Constructor */ && ts.isClassLike(node.parent.parent); + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; })(ts || (ts = {})); /// /// @@ -6627,7 +6876,7 @@ var ts; var NodeConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 248 /* SourceFile */) { + if (kind === 250 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else { @@ -6677,7 +6926,7 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 246 /* ShorthandPropertyAssignment */: + case 248 /* ShorthandPropertyAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -6687,9 +6936,9 @@ var ts; case 138 /* Parameter */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 247 /* PropertyAssignment */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -6713,9 +6962,9 @@ var ts; case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 176 /* ArrowFunction */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -6745,271 +6994,271 @@ var ts; return visitNodes(cbNodes, node.types); case 160 /* ParenthesizedType */: return visitNode(cbNode, node.type); - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: + case 163 /* ObjectBindingPattern */: + case 164 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return visitNodes(cbNodes, node.elements); - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return visitNodes(cbNodes, node.properties); - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 167 /* ElementAccessExpression */: + case 169 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 170 /* TaggedTemplateExpression */: + case 172 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 171 /* TypeAssertionExpression */: + case 173 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 175 /* DeleteExpression */: + case 177 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 176 /* TypeOfExpression */: + case 178 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 177 /* VoidExpression */: + case 179 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 184 /* YieldExpression */: + case 186 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 178 /* AwaitExpression */: + case 180 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 180 /* PostfixUnaryExpression */: + case 182 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 189 /* AsExpression */: + case 191 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 185 /* SpreadElementExpression */: + case 187 /* SpreadElementExpression */: return visitNode(cbNode, node.expression); - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 194 /* Block */: + case 221 /* ModuleBlock */: return visitNodes(cbNodes, node.statements); - case 248 /* SourceFile */: + case 250 /* SourceFile */: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 212 /* VariableDeclarationList */: + case 214 /* VariableDeclarationList */: return visitNodes(cbNodes, node.declarations); - case 195 /* ExpressionStatement */: + case 197 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 196 /* IfStatement */: + case 198 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 197 /* DoStatement */: + case 199 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 198 /* WhileStatement */: + case 200 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 199 /* ForStatement */: + case 201 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 200 /* ForInStatement */: + case 202 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 201 /* ForOfStatement */: + case 203 /* ForOfStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 204 /* ContinueStatement */: + case 205 /* BreakStatement */: return visitNode(cbNode, node.label); - case 204 /* ReturnStatement */: + case 206 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 205 /* WithStatement */: + case 207 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 220 /* CaseBlock */: + case 222 /* CaseBlock */: return visitNodes(cbNodes, node.clauses); - case 241 /* CaseClause */: + case 243 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 242 /* DefaultClause */: + case 244 /* DefaultClause */: return visitNodes(cbNodes, node.statements); - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 208 /* ThrowStatement */: + case 210 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 209 /* TryStatement */: + case 211 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); case 139 /* Decorator */: return visitNode(cbNode, node.expression); - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 216 /* TypeAliasDeclaration */: + case 218 /* TypeAliasDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.members); - case 247 /* EnumMember */: + case 249 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 223 /* ImportClause */: + case 225 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 224 /* NamespaceImport */: + case 226 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 225 /* NamedImports */: - case 229 /* NamedExports */: + case 227 /* NamedImports */: + case 231 /* NamedExports */: return visitNodes(cbNodes, node.elements); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 228 /* ImportSpecifier */: + case 232 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 183 /* TemplateExpression */: + case 185 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 190 /* TemplateSpan */: + case 192 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); case 136 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 243 /* HeritageClause */: + case 245 /* HeritageClause */: return visitNodes(cbNodes, node.types); - case 188 /* ExpressionWithTypeArguments */: + case 190 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 232 /* ExternalModuleReference */: + case 234 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 231 /* MissingDeclaration */: + case 233 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); - case 233 /* JsxElement */: + case 235 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 234 /* JsxSelfClosingElement */: - case 235 /* JsxOpeningElement */: + case 236 /* JsxSelfClosingElement */: + case 237 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 238 /* JsxAttribute */: + case 240 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 239 /* JsxSpreadAttribute */: + case 241 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 240 /* JsxExpression */: + case 242 /* JsxExpression */: return visitNode(cbNode, node.expression); - case 237 /* JsxClosingElement */: + case 239 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 249 /* JSDocTypeExpression */: + case 251 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 253 /* JSDocUnionType */: + case 255 /* JSDocUnionType */: return visitNodes(cbNodes, node.types); - case 254 /* JSDocTupleType */: + case 256 /* JSDocTupleType */: return visitNodes(cbNodes, node.types); - case 252 /* JSDocArrayType */: + case 254 /* JSDocArrayType */: return visitNode(cbNode, node.elementType); - case 256 /* JSDocNonNullableType */: + case 258 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 255 /* JSDocNullableType */: + case 257 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 257 /* JSDocRecordType */: + case 259 /* JSDocRecordType */: return visitNodes(cbNodes, node.members); - case 259 /* JSDocTypeReference */: + case 261 /* JSDocTypeReference */: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); - case 260 /* JSDocOptionalType */: + case 262 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 261 /* JSDocFunctionType */: + case 263 /* JSDocFunctionType */: return visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 262 /* JSDocVariadicType */: + case 264 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 263 /* JSDocConstructorType */: + case 265 /* JSDocConstructorType */: return visitNode(cbNode, node.type); - case 264 /* JSDocThisType */: + case 266 /* JSDocThisType */: return visitNode(cbNode, node.type); - case 258 /* JSDocRecordMember */: + case 260 /* JSDocRecordMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 265 /* JSDocComment */: + case 267 /* JSDocComment */: return visitNodes(cbNodes, node.tags); - case 267 /* JSDocParameterTag */: + case 269 /* JSDocParameterTag */: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 268 /* JSDocReturnTag */: + case 270 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 269 /* JSDocTypeTag */: + case 271 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 270 /* JSDocTemplateTag */: + case 272 /* JSDocTemplateTag */: return visitNodes(cbNodes, node.typeParameters); } } @@ -7150,6 +7399,10 @@ var ts; return result; } Parser.parseSourceFile = parseSourceFile; + function getLanguageVariant(fileName) { + // .tsx and .jsx files are treated as jsx language variant. + return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx") ? 1 /* JSX */ : 0 /* Standard */; + } function initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); @@ -7166,7 +7419,7 @@ var ts; scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(ts.allowsJsxExpressions(fileName) ? 1 /* JSX */ : 0 /* Standard */); + scanner.setLanguageVariant(getLanguageVariant(fileName)); } function clearState() { // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. @@ -7213,8 +7466,8 @@ var ts; // Add additional cases as necessary depending on how we see JSDoc comments used // in the wild. switch (node.kind) { - case 193 /* VariableStatement */: - case 213 /* FunctionDeclaration */: + case 195 /* VariableStatement */: + case 215 /* FunctionDeclaration */: case 138 /* Parameter */: addJSDocComment(node); } @@ -7258,14 +7511,14 @@ var ts; function createSourceFile(fileName, languageVersion) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(248 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(250 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 /* DeclarationFile */ : 0; - sourceFile.languageVariant = ts.allowsJsxExpressions(sourceFile.fileName) ? 1 /* JSX */ : 0 /* Standard */; + sourceFile.languageVariant = getLanguageVariant(sourceFile.fileName); return sourceFile; } function setContextFlag(val, flag) { @@ -7298,10 +7551,10 @@ var ts; var contextFlagsToClear = context & contextFlags; if (contextFlagsToClear) { // clear the requested context flags - setContextFlag(false, contextFlagsToClear); + setContextFlag(/*val*/ false, contextFlagsToClear); var result = func(); // restore the context flags we just cleared - setContextFlag(true, contextFlagsToClear); + setContextFlag(/*val*/ true, contextFlagsToClear); return result; } // no need to do anything special as we are not in any of the requested contexts @@ -7317,10 +7570,10 @@ var ts; var contextFlagsToSet = context & ~contextFlags; if (contextFlagsToSet) { // set the requested context flags - setContextFlag(true, contextFlagsToSet); + setContextFlag(/*val*/ true, contextFlagsToSet); var result = func(); // reset the context flags we just set - setContextFlag(false, contextFlagsToSet); + setContextFlag(/*val*/ false, contextFlagsToSet); return result; } // no need to do anything special as we are already in all of the requested contexts @@ -7335,9 +7588,6 @@ var ts; function doInYieldContext(func) { return doInsideOfContext(2 /* Yield */, func); } - function doOutsideOfYieldContext(func) { - return doOutsideOfContext(2 /* Yield */, func); - } function doInDecoratorContext(func) { return doInsideOfContext(4 /* Decorator */, func); } @@ -7350,9 +7600,6 @@ var ts; function doInYieldAndAwaitContext(func) { return doInsideOfContext(2 /* Yield */ | 8 /* Await */, func); } - function doOutsideOfYieldAndAwaitContext(func) { - return doOutsideOfContext(2 /* Yield */ | 8 /* Await */, func); - } function inContext(flags) { return (contextFlags & flags) !== 0; } @@ -7396,9 +7643,6 @@ var ts; function nextToken() { return token = scanner.scan(); } - function getTokenPos(pos) { - return ts.skipTrivia(sourceText, pos); - } function reScanGreaterToken() { return token = scanner.reScanGreaterToken(); } @@ -7605,10 +7849,10 @@ var ts; return parseIdentifierName(); } function parsePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ true); + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); } function parseSimplePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ false); + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false); } function isSimplePropertyName() { return token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token); @@ -7629,6 +7873,13 @@ var ts; function parseContextualModifier(t) { return token === t && tryParse(nextTokenCanFollowModifier); } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } function nextTokenCanFollowModifier() { if (token === 74 /* ConstKeyword */) { // 'const' is only a modifier if followed by 'enum'. @@ -7648,14 +7899,10 @@ var ts; nextToken(); return canFollowModifier(); } - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); + return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifier(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { return token === 19 /* OpenBracketToken */ @@ -7861,7 +8108,7 @@ var ts; function isInSomeParsingContext() { for (var kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & (1 << kind)) { - if (isListElement(kind, /* inErrorRecovery */ true) || isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; } } @@ -7875,7 +8122,7 @@ var ts; var result = []; result.pos = getNodePos(); while (!isListTerminator(kind)) { - if (isListElement(kind, /* inErrorRecovery */ false)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); result.push(element); continue; @@ -8020,7 +8267,7 @@ var ts; case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 141 /* PropertyDeclaration */: - case 191 /* SemicolonClassElement */: + case 193 /* SemicolonClassElement */: return true; case 143 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal @@ -8037,8 +8284,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: return true; } } @@ -8047,42 +8294,42 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: - case 193 /* VariableStatement */: - case 192 /* Block */: - case 196 /* IfStatement */: - case 195 /* ExpressionStatement */: - case 208 /* ThrowStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 194 /* EmptyStatement */: - case 209 /* TryStatement */: - case 207 /* LabeledStatement */: - case 197 /* DoStatement */: - case 210 /* DebuggerStatement */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: - case 227 /* ExportAssignment */: - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 216 /* TypeAliasDeclaration */: + case 215 /* FunctionDeclaration */: + case 195 /* VariableStatement */: + case 194 /* Block */: + case 198 /* IfStatement */: + case 197 /* ExpressionStatement */: + case 210 /* ThrowStatement */: + case 206 /* ReturnStatement */: + case 208 /* SwitchStatement */: + case 205 /* BreakStatement */: + case 204 /* ContinueStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 201 /* ForStatement */: + case 200 /* WhileStatement */: + case 207 /* WithStatement */: + case 196 /* EmptyStatement */: + case 211 /* TryStatement */: + case 209 /* LabeledStatement */: + case 199 /* DoStatement */: + case 212 /* DebuggerStatement */: + case 224 /* ImportDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 230 /* ExportDeclaration */: + case 229 /* ExportAssignment */: + case 220 /* ModuleDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: + case 218 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 247 /* EnumMember */; + return node.kind === 249 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { @@ -8098,7 +8345,7 @@ var ts; return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 211 /* VariableDeclaration */) { + if (node.kind !== 213 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -8174,7 +8421,7 @@ var ts; result.pos = getNodePos(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { - if (isListElement(kind, /* inErrorRecovery */ false)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(24 /* CommaToken */)) { @@ -8269,14 +8516,14 @@ var ts; // Report that we need an identifier. However, report it right after the dot, // and not on the next token. This is because the next token might actually // be an identifier and the error would be quite confusing. - return createMissingNode(69 /* Identifier */, /*reportAtCurrentToken*/ true, ts.Diagnostics.Identifier_expected); + return createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(183 /* TemplateExpression */); - template.head = parseLiteralNode(); + var template = createNode(185 /* TemplateExpression */); + template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = []; templateSpans.pos = getNodePos(); @@ -8288,12 +8535,12 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(190 /* TemplateSpan */); + var span = createNode(192 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token === 16 /* CloseBraceToken */) { reScanTemplateToken(); - literal = parseLiteralNode(); + literal = parseTemplateLiteralFragment(); } else { literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); @@ -8301,8 +8548,17 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(162 /* StringLiteralType */, /*internName*/ true); + } function parseLiteralNode(internName) { - var node = createNode(token); + return parseLiteralLikeNode(token, internName); + } + function parseTemplateLiteralFragment() { + return parseLiteralLikeNode(token, /*internName*/ false); + } + function parseLiteralLikeNode(kind, internName) { + var node = createNode(kind); var text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -8331,11 +8587,7 @@ var ts; function parseTypeReferenceOrTypePredicate() { var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); if (typeName.kind === 69 /* Identifier */ && token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var node_1 = createNode(150 /* TypePredicate */, typeName.pos); - node_1.parameterName = typeName; - node_1.type = parseType(); - return finishNode(node_1); + return parseTypePredicate(typeName); } var node = createNode(151 /* TypeReference */, typeName.pos); node.typeName = typeName; @@ -8344,6 +8596,18 @@ var ts; } return finishNode(node); } + function parseTypePredicate(lhs) { + nextToken(); + var node = createNode(150 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(161 /* ThisType */); + nextToken(); + return finishNode(node); + } function parseTypeQuery() { var node = createNode(154 /* TypeQuery */); parseExpected(101 /* TypeOfKeyword */); @@ -8386,7 +8650,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifier(token) || token === 55 /* AtToken */; + return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 /* AtToken */; } function setModifiers(node, modifiers) { if (modifiers) { @@ -8402,7 +8666,7 @@ var ts; // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifier(token)) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { // in cases like // 'use strict' // function foo(static) @@ -8523,7 +8787,7 @@ var ts; if (token === 22 /* DotDotDotToken */ || token === 20 /* CloseBracketToken */) { return true; } - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -8580,6 +8844,12 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); + if (token === 56 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + property.initializer = parseNonParameterInitializer(); + } parseTypeMemberSemicolon(); return finishNode(property); } @@ -8591,7 +8861,7 @@ var ts; case 19 /* OpenBracketToken */: return true; default: - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { var result = lookAhead(isStartOfIndexSignatureDeclaration); if (result) { return result; @@ -8601,7 +8871,7 @@ var ts; } } function isStartOfIndexSignatureDeclaration() { - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { nextToken(); } return isIndexSignature(); @@ -8639,7 +8909,7 @@ var ts; // when incrementally parsing as the parser will produce the Index declaration // if it has the same text regardless of whether it is inside a class or an // object type. - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { var result = tryParse(parseIndexSignatureWithModifiers); if (result) { return result; @@ -8713,10 +8983,18 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReferenceOrTypePredicate(); case 9 /* StringLiteral */: - return parseLiteralNode(/*internName*/ true); + return parseStringLiteralTypeNode(); case 103 /* VoidKeyword */: - case 97 /* ThisKeyword */: return parseTokenNode(); + case 97 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } case 101 /* TypeOfKeyword */: return parseTypeQuery(); case 15 /* OpenBraceToken */: @@ -8801,11 +9079,11 @@ var ts; // ( ... return true; } - if (isIdentifier() || ts.isModifier(token)) { + if (isIdentifier() || ts.isModifierKind(token)) { nextToken(); if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */ || - isIdentifier() || ts.isModifier(token)) { + isIdentifier() || ts.isModifierKind(token)) { // ( id : // ( id , // ( id ? @@ -8906,9 +9184,6 @@ var ts; token !== 55 /* AtToken */ && isStartOfExpression(); } - function allowInAndParseExpression() { - return allowInAnd(parseExpression); - } function parseExpression() { // Expression[in]: // AssignmentExpression[in] @@ -8916,7 +9191,7 @@ var ts; // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; @@ -8924,7 +9199,7 @@ var ts; expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } return expr; } @@ -9029,7 +9304,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(184 /* YieldExpression */); + var node = createNode(186 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -9049,14 +9324,14 @@ var ts; } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(174 /* ArrowFunction */, identifier.pos); + var node = createNode(176 /* ArrowFunction */, identifier.pos); var parameter = createNode(138 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = [parameter]; node.parameters.pos = parameter.pos; node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, false, ts.Diagnostics._0_expected, "=>"); + node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ false); return finishNode(node); } @@ -9160,7 +9435,7 @@ var ts; return 1 /* True */; } // This *could* be a parenthesized arrow function. - // Return Unknown to const the caller know. + // Return Unknown to let the caller know. return 2 /* Unknown */; } else { @@ -9202,7 +9477,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(174 /* ArrowFunction */); + var node = createNode(176 /* ArrowFunction */); setModifiers(node, parseModifiersForArrowFunction()); var isAsync = !!(node.flags & 256 /* Async */); // Arrow functions are never generators. @@ -9246,7 +9521,7 @@ var ts; // user meant to supply a block. For example, if the user wrote: // // a => - // const v = 0; + // let v = 0; // } // // they may be missing an open brace. Check to see if that's the case so we can @@ -9268,7 +9543,7 @@ var ts; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(182 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(184 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -9389,39 +9664,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(181 /* BinaryExpression */, left.pos); + var node = createNode(183 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(189 /* AsExpression */, left.pos); + var node = createNode(191 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(179 /* PrefixUnaryExpression */); + var node = createNode(181 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(175 /* DeleteExpression */); + var node = createNode(177 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(176 /* TypeOfExpression */); + var node = createNode(178 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(177 /* VoidExpression */); + var node = createNode(179 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -9437,7 +9712,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(178 /* AwaitExpression */); + var node = createNode(180 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -9463,7 +9738,7 @@ var ts; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === 38 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 171 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 173 /* 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); } else { @@ -9553,7 +9828,7 @@ var ts; */ function parseIncrementExpression() { if (token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) { - var node = createNode(179 /* PrefixUnaryExpression */); + var node = createNode(181 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -9566,7 +9841,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(180 /* PostfixUnaryExpression */, expression.pos); + var node = createNode(182 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -9670,24 +9945,37 @@ var ts; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(166 /* PropertyAccessExpression */, expression.pos); + var node = createNode(168 /* PropertyAccessExpression */, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 69 /* Identifier */) { + return lhs.text === rhs.text; + } + return lhs.right.text === rhs.right.text && + tagNamesAreEquivalent(lhs.left, rhs.left); + } function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 235 /* JsxOpeningElement */) { - var node = createNode(233 /* JsxElement */, opening.pos); + if (opening.kind === 237 /* JsxOpeningElement */) { + var node = createNode(235 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 236 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -9702,7 +9990,7 @@ var ts; var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(181 /* BinaryExpression */, result.pos); + var badNode = createNode(183 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -9714,13 +10002,13 @@ var ts; return result; } function parseJsxText() { - var node = createNode(236 /* JsxText */, scanner.getStartPos()); + var node = createNode(238 /* JsxText */, scanner.getStartPos()); token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token) { - case 236 /* JsxText */: + case 238 /* JsxText */: return parseJsxText(); case 15 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); @@ -9737,10 +10025,13 @@ var ts; while (true) { token = scanner.reScanJsxToken(); if (token === 26 /* LessThanSlashToken */) { + // Closing tag break; } else if (token === 1 /* EndOfFileToken */) { - parseErrorAtCurrentToken(ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + // 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)); break; } result.push(parseJsxChild()); @@ -9759,7 +10050,7 @@ var ts; // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(235 /* JsxOpeningElement */, fullStart); + node = createNode(237 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { @@ -9768,10 +10059,10 @@ var ts; parseExpected(27 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(234 /* JsxSelfClosingElement */, fullStart); + node = createNode(236 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -9790,16 +10081,16 @@ var ts; return elementName; } function parseJsxExpression(inExpressionContext) { - var node = createNode(240 /* JsxExpression */); + var node = createNode(242 /* JsxExpression */); parseExpected(15 /* OpenBraceToken */); if (token !== 16 /* CloseBraceToken */) { - node.expression = parseExpression(); + node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { parseExpected(16 /* CloseBraceToken */); } else { - parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*advance*/ false); + parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); @@ -9809,7 +10100,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(238 /* JsxAttribute */); + var node = createNode(240 /* JsxAttribute */); node.name = parseIdentifierName(); if (parseOptional(56 /* EqualsToken */)) { switch (token) { @@ -9824,7 +10115,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(239 /* JsxSpreadAttribute */); + var node = createNode(241 /* JsxSpreadAttribute */); parseExpected(15 /* OpenBraceToken */); parseExpected(22 /* DotDotDotToken */); node.expression = parseExpression(); @@ -9832,20 +10123,20 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(237 /* JsxClosingElement */); + var node = createNode(239 /* JsxClosingElement */); parseExpected(26 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { parseExpected(27 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(171 /* TypeAssertionExpression */); + var node = createNode(173 /* TypeAssertionExpression */); parseExpected(25 /* LessThanToken */); node.type = parseType(); parseExpected(27 /* GreaterThanToken */); @@ -9856,7 +10147,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(21 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(166 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(168 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -9865,7 +10156,7 @@ var ts; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(19 /* OpenBracketToken */)) { - var indexedAccess = createNode(167 /* ElementAccessExpression */, expression.pos); + var indexedAccess = createNode(169 /* ElementAccessExpression */, expression.pos); 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. @@ -9881,7 +10172,7 @@ var ts; continue; } if (token === 11 /* NoSubstitutionTemplateLiteral */ || token === 12 /* TemplateHead */) { - var tagExpression = createNode(170 /* TaggedTemplateExpression */, expression.pos); + var tagExpression = createNode(172 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 11 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() @@ -9904,7 +10195,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(168 /* CallExpression */, expression.pos); + var callExpr = createNode(170 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -9912,7 +10203,7 @@ var ts; continue; } else if (token === 17 /* OpenParenToken */) { - var callExpr = createNode(168 /* CallExpression */, expression.pos); + var callExpr = createNode(170 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -10022,28 +10313,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(172 /* ParenthesizedExpression */); + var node = createNode(174 /* ParenthesizedExpression */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(185 /* SpreadElementExpression */); + var node = createNode(187 /* SpreadElementExpression */); parseExpected(22 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 22 /* DotDotDotToken */ ? parseSpreadElement() : - token === 24 /* CommaToken */ ? createNode(187 /* OmittedExpression */) : + token === 24 /* CommaToken */ ? createNode(189 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(164 /* ArrayLiteralExpression */); + var node = createNode(166 /* ArrayLiteralExpression */); parseExpected(19 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) node.flags |= 1024 /* MultiLine */; @@ -10070,7 +10361,6 @@ var ts; } var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); - var nameToken = token; var propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); @@ -10084,7 +10374,7 @@ var ts; // 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 */); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(246 /* ShorthandPropertyAssignment */, fullStart); + var shorthandDeclaration = createNode(248 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; var equalsToken = parseOptionalToken(56 /* EqualsToken */); @@ -10095,7 +10385,8 @@ var ts; return finishNode(shorthandDeclaration); } else { - var propertyAssignment = createNode(245 /* PropertyAssignment */, fullStart); + var propertyAssignment = createNode(247 /* PropertyAssignment */, fullStart); + propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(54 /* ColonToken */); @@ -10104,7 +10395,7 @@ var ts; } } function parseObjectLiteralExpression() { - var node = createNode(165 /* ObjectLiteralExpression */); + var node = createNode(167 /* ObjectLiteralExpression */); parseExpected(15 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.flags |= 1024 /* MultiLine */; @@ -10121,9 +10412,9 @@ var ts; // function BindingIdentifier[opt](FormalParameters){ FunctionBody } var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } - var node = createNode(173 /* FunctionExpression */); + var node = createNode(175 /* FunctionExpression */); setModifiers(node, parseModifiers()); parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); @@ -10137,7 +10428,7 @@ var ts; fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } return finishNode(node); } @@ -10145,7 +10436,7 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(169 /* NewExpression */); + var node = createNode(171 /* NewExpression */); parseExpected(92 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -10156,7 +10447,7 @@ var ts; } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(192 /* Block */); + var node = createNode(194 /* Block */); if (parseExpected(15 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); @@ -10175,23 +10466,23 @@ var ts; // arrow function. The body of the function is not in [Decorator] context. var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return block; } function parseEmptyStatement() { - var node = createNode(194 /* EmptyStatement */); + var node = createNode(196 /* EmptyStatement */); parseExpected(23 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(196 /* IfStatement */); + var node = createNode(198 /* IfStatement */); parseExpected(88 /* IfKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -10201,7 +10492,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(197 /* DoStatement */); + var node = createNode(199 /* DoStatement */); parseExpected(79 /* DoKeyword */); node.statement = parseStatement(); parseExpected(104 /* WhileKeyword */); @@ -10216,7 +10507,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(198 /* WhileStatement */); + var node = createNode(200 /* WhileStatement */); parseExpected(104 /* WhileKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -10239,21 +10530,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(90 /* InKeyword */)) { - var forInStatement = createNode(200 /* ForInStatement */, pos); + var forInStatement = createNode(202 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else if (parseOptional(134 /* OfKeyword */)) { - var forOfStatement = createNode(201 /* ForOfStatement */, pos); + var forOfStatement = createNode(203 /* ForOfStatement */, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(18 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(199 /* ForStatement */, pos); + var forStatement = createNode(201 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(23 /* SemicolonToken */); if (token !== 23 /* SemicolonToken */ && token !== 18 /* CloseParenToken */) { @@ -10271,7 +10562,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); + parseExpected(kind === 205 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -10279,7 +10570,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(204 /* ReturnStatement */); + var node = createNode(206 /* ReturnStatement */); parseExpected(94 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -10288,7 +10579,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(205 /* WithStatement */); + var node = createNode(207 /* WithStatement */); parseExpected(105 /* WithKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -10297,7 +10588,7 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(241 /* CaseClause */); + var node = createNode(243 /* CaseClause */); parseExpected(71 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(54 /* ColonToken */); @@ -10305,7 +10596,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(242 /* DefaultClause */); + var node = createNode(244 /* DefaultClause */); parseExpected(77 /* DefaultKeyword */); parseExpected(54 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); @@ -10315,12 +10606,12 @@ var ts; return token === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(206 /* SwitchStatement */); + var node = createNode(208 /* SwitchStatement */); parseExpected(96 /* SwitchKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); - var caseBlock = createNode(220 /* CaseBlock */, scanner.getStartPos()); + var caseBlock = createNode(222 /* CaseBlock */, scanner.getStartPos()); parseExpected(15 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(16 /* CloseBraceToken */); @@ -10335,7 +10626,7 @@ var ts; // directly as that might consume an expression on the following line. // We just return 'undefined' in that case. The actual error will be reported in the // grammar walker. - var node = createNode(208 /* ThrowStatement */); + var node = createNode(210 /* ThrowStatement */); parseExpected(98 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -10343,7 +10634,7 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(209 /* TryStatement */); + var node = createNode(211 /* TryStatement */); parseExpected(100 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); node.catchClause = token === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -10356,7 +10647,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(244 /* CatchClause */); + var result = createNode(246 /* CatchClause */); parseExpected(72 /* CatchKeyword */); if (parseExpected(17 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); @@ -10366,7 +10657,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(210 /* DebuggerStatement */); + var node = createNode(212 /* DebuggerStatement */); parseExpected(76 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -10378,13 +10669,13 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 69 /* Identifier */ && parseOptional(54 /* ColonToken */)) { - var labeledStatement = createNode(207 /* LabeledStatement */, fullStart); + var labeledStatement = createNode(209 /* LabeledStatement */, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - var expressionStatement = createNode(195 /* ExpressionStatement */, fullStart); + var expressionStatement = createNode(197 /* ExpressionStatement */, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); @@ -10558,9 +10849,9 @@ var ts; case 86 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 75 /* ContinueKeyword */: - return parseBreakOrContinueStatement(202 /* ContinueStatement */); + return parseBreakOrContinueStatement(204 /* ContinueStatement */); case 70 /* BreakKeyword */: - return parseBreakOrContinueStatement(203 /* BreakStatement */); + return parseBreakOrContinueStatement(205 /* BreakStatement */); case 94 /* ReturnKeyword */: return parseReturnStatement(); case 105 /* WithKeyword */: @@ -10633,7 +10924,7 @@ var ts; if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var node = createMissingNode(231 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(233 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; setModifiers(node, modifiers); @@ -10655,16 +10946,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token === 24 /* CommaToken */) { - return createNode(187 /* OmittedExpression */); + return createNode(189 /* OmittedExpression */); } - var node = createNode(163 /* BindingElement */); + var node = createNode(165 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(/*inParameter*/ false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(163 /* BindingElement */); + var node = createNode(165 /* BindingElement */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== 54 /* ColonToken */) { @@ -10679,14 +10970,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(161 /* ObjectBindingPattern */); + var node = createNode(163 /* ObjectBindingPattern */); parseExpected(15 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(16 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(162 /* ArrayBindingPattern */); + var node = createNode(164 /* ArrayBindingPattern */); parseExpected(19 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(20 /* CloseBracketToken */); @@ -10705,7 +10996,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(211 /* VariableDeclaration */); + var node = createNode(213 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -10714,7 +11005,7 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(212 /* VariableDeclarationList */); + var node = createNode(214 /* VariableDeclarationList */); switch (token) { case 102 /* VarKeyword */: break; @@ -10752,7 +11043,7 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 18 /* CloseParenToken */; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(193 /* VariableStatement */, fullStart); + var node = createNode(195 /* VariableStatement */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); @@ -10760,7 +11051,7 @@ var ts; return finishNode(node); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(213 /* FunctionDeclaration */, fullStart); + var node = createNode(215 /* FunctionDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(87 /* FunctionKeyword */); @@ -10858,7 +11149,7 @@ var ts; return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. - while (ts.isModifier(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 @@ -10919,7 +11210,7 @@ var ts; } if (!decorators) { decorators = []; - decorators.pos = scanner.getStartPos(); + decorators.pos = decoratorStart; } var decorator = createNode(139 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); @@ -10930,14 +11221,30 @@ var ts; } return decorators; } - function parseModifiers() { + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token; - if (!parseAnyContextualModifier()) { - break; + 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)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } } if (!modifiers) { modifiers = []; @@ -10970,13 +11277,13 @@ var ts; } function parseClassElement() { if (token === 23 /* SemicolonToken */) { - var result = createNode(191 /* SemicolonClassElement */); + var result = createNode(193 /* SemicolonClassElement */); nextToken(); return finishNode(result); } var fullStart = getNodePos(); var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; @@ -11008,10 +11315,10 @@ var ts; return parseClassDeclarationOrExpression( /*fullStart*/ scanner.getStartPos(), /*decorators*/ undefined, - /*modifiers*/ undefined, 186 /* ClassExpression */); + /*modifiers*/ undefined, 188 /* ClassExpression */); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 214 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 216 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); @@ -11036,8 +11343,8 @@ var ts; // implements is a future reserved word so // 'class implements' might mean either // - class expression with omitted name, 'implements' starts heritage clause - // - class with name 'implements' - // 'isImplementsClause' helps to disambiguate between these two cases + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases return isIdentifier() && !isImplementsClause() ? parseIdentifier() : undefined; @@ -11053,12 +11360,9 @@ var ts; } return undefined; } - function parseHeritageClausesWorker() { - return parseList(20 /* HeritageClauses */, parseHeritageClause); - } function parseHeritageClause() { if (token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */) { - var node = createNode(243 /* HeritageClause */); + var node = createNode(245 /* HeritageClause */); node.token = token; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); @@ -11067,7 +11371,7 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(188 /* ExpressionWithTypeArguments */); + var node = createNode(190 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); @@ -11081,7 +11385,7 @@ var ts; return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(215 /* InterfaceDeclaration */, fullStart); + var node = createNode(217 /* InterfaceDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(107 /* InterfaceKeyword */); @@ -11092,7 +11396,7 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(216 /* TypeAliasDeclaration */, fullStart); + var node = createNode(218 /* TypeAliasDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(132 /* TypeKeyword */); @@ -11108,13 +11412,13 @@ var ts; // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNode(247 /* EnumMember */, scanner.getStartPos()); + var node = createNode(249 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(217 /* EnumDeclaration */, fullStart); + var node = createNode(219 /* EnumDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(81 /* EnumKeyword */); @@ -11129,7 +11433,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(219 /* ModuleBlock */, scanner.getStartPos()); + var node = createNode(221 /* ModuleBlock */, scanner.getStartPos()); if (parseExpected(15 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); @@ -11140,7 +11444,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(218 /* ModuleDeclaration */, fullStart); + var node = createNode(220 /* ModuleDeclaration */, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 65536 /* Namespace */; @@ -11154,7 +11458,7 @@ var ts; return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(218 /* ModuleDeclaration */, fullStart); + var node = createNode(220 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parseLiteralNode(/*internName*/ true); @@ -11184,11 +11488,6 @@ var ts; function nextTokenIsSlash() { return nextToken() === 39 /* SlashToken */; } - function nextTokenIsCommaOrFromKeyword() { - nextToken(); - return token === 24 /* CommaToken */ || - token === 133 /* FromKeyword */; - } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(89 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); @@ -11199,7 +11498,7 @@ var ts; // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - var importEqualsDeclaration = createNode(221 /* ImportEqualsDeclaration */, fullStart); + var importEqualsDeclaration = createNode(223 /* ImportEqualsDeclaration */, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -11210,7 +11509,7 @@ var ts; } } // Import statement - var importDeclaration = createNode(222 /* ImportDeclaration */, fullStart); + var importDeclaration = createNode(224 /* ImportDeclaration */, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); // ImportDeclaration: @@ -11233,7 +11532,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(223 /* ImportClause */, fullStart); + var importClause = createNode(225 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -11243,7 +11542,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(24 /* CommaToken */)) { - importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(225 /* NamedImports */); + importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(227 /* NamedImports */); } return finishNode(importClause); } @@ -11253,7 +11552,7 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(232 /* ExternalModuleReference */); + var node = createNode(234 /* ExternalModuleReference */); parseExpected(127 /* RequireKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = parseModuleSpecifier(); @@ -11261,21 +11560,22 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - // We allow arbitrary expressions here, even though the grammar only allows string - // literals. We check to ensure that it is only a string literal later in the grammar - // walker. - var result = parseExpression(); - // Ensure the string being required is in our 'identifier' table. This will ensure - // that features like 'find refs' will look inside this file when search for its name. - if (result.kind === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */) { + var result = parseLiteralNode(); internIdentifier(result.text); + return result; + } + else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. + return parseExpression(); } - return result; } function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(224 /* NamespaceImport */); + var namespaceImport = createNode(226 /* NamespaceImport */); parseExpected(37 /* AsteriskToken */); parseExpected(116 /* AsKeyword */); namespaceImport.name = parseIdentifier(); @@ -11290,14 +11590,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(21 /* ImportOrExportSpecifiers */, kind === 225 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); + node.elements = parseBracketedList(21 /* ImportOrExportSpecifiers */, kind === 227 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(230 /* ExportSpecifier */); + return parseImportOrExportSpecifier(232 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(226 /* ImportSpecifier */); + return parseImportOrExportSpecifier(228 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -11322,14 +11622,14 @@ var ts; else { node.name = identifierName; } - if (kind === 226 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 228 /* ImportSpecifier */ && checkIdentifierIsKeyword) { // Report error identifier expected parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228 /* ExportDeclaration */, fullStart); + var node = createNode(230 /* ExportDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(37 /* AsteriskToken */)) { @@ -11337,7 +11637,7 @@ var ts; node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(229 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(231 /* NamedExports */); // 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. @@ -11350,7 +11650,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(227 /* ExportAssignment */, fullStart); + var node = createNode(229 /* ExportAssignment */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(56 /* EqualsToken */)) { @@ -11373,11 +11673,13 @@ var ts; // reference comment. while (true) { var kind = triviaScanner.scan(); - if (kind === 5 /* WhitespaceTrivia */ || kind === 4 /* NewLineTrivia */ || kind === 3 /* MultiLineCommentTrivia */) { - continue; - } if (kind !== 2 /* SingleLineCommentTrivia */) { - break; + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } } var range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; var comment = sourceText.substring(range.pos, range.end); @@ -11423,10 +11725,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return node.flags & 2 /* Export */ - || node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 232 /* ExternalModuleReference */ - || node.kind === 222 /* ImportDeclaration */ - || node.kind === 227 /* ExportAssignment */ - || node.kind === 228 /* ExportDeclaration */ + || node.kind === 223 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 234 /* ExternalModuleReference */ + || node.kind === 224 /* ImportDeclaration */ + || node.kind === 229 /* ExportAssignment */ + || node.kind === 230 /* ExportDeclaration */ ? node : undefined; }); @@ -11501,7 +11803,7 @@ var ts; scanner.setText(sourceText, start, length); // Prime the first token for us to start processing. token = nextToken(); - var result = createNode(249 /* JSDocTypeExpression */); + var result = createNode(251 /* JSDocTypeExpression */); parseExpected(15 /* OpenBraceToken */); result.type = parseJSDocTopLevelType(); parseExpected(16 /* CloseBraceToken */); @@ -11512,12 +11814,12 @@ var ts; function parseJSDocTopLevelType() { var type = parseJSDocType(); if (token === 47 /* BarToken */) { - var unionType = createNode(253 /* JSDocUnionType */, type.pos); + var unionType = createNode(255 /* JSDocUnionType */, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } if (token === 56 /* EqualsToken */) { - var optionalType = createNode(260 /* JSDocOptionalType */, type.pos); + var optionalType = createNode(262 /* JSDocOptionalType */, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -11528,20 +11830,20 @@ var ts; var type = parseBasicTypeExpression(); while (true) { if (token === 19 /* OpenBracketToken */) { - var arrayType = createNode(252 /* JSDocArrayType */, type.pos); + var arrayType = createNode(254 /* JSDocArrayType */, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20 /* CloseBracketToken */); type = finishNode(arrayType); } else if (token === 53 /* QuestionToken */) { - var nullableType = createNode(255 /* JSDocNullableType */, type.pos); + var nullableType = createNode(257 /* JSDocNullableType */, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } else if (token === 49 /* ExclamationToken */) { - var nonNullableType = createNode(256 /* JSDocNonNullableType */, type.pos); + var nonNullableType = createNode(258 /* JSDocNonNullableType */, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -11586,27 +11888,27 @@ var ts; return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(264 /* JSDocThisType */); + var result = createNode(266 /* JSDocThisType */); nextToken(); parseExpected(54 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(263 /* JSDocConstructorType */); + var result = createNode(265 /* JSDocConstructorType */); nextToken(); parseExpected(54 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(262 /* JSDocVariadicType */); + var result = createNode(264 /* JSDocVariadicType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(261 /* JSDocFunctionType */); + var result = createNode(263 /* JSDocFunctionType */); nextToken(); parseExpected(17 /* OpenParenToken */); result.parameters = parseDelimitedList(22 /* JSDocFunctionParameters */, parseJSDocParameter); @@ -11623,14 +11925,8 @@ var ts; parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocOptionalType(type) { - var result = createNode(260 /* JSDocOptionalType */, type.pos); - nextToken(); - result.type = type; - return finishNode(result); - } function parseJSDocTypeReference() { - var result = createNode(259 /* JSDocTypeReference */); + var result = createNode(261 /* JSDocTypeReference */); result.name = parseSimplePropertyName(); while (parseOptional(21 /* DotToken */)) { if (token === 25 /* LessThanToken */) { @@ -11666,7 +11962,7 @@ var ts; return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(257 /* JSDocRecordType */); + var result = createNode(259 /* JSDocRecordType */); nextToken(); result.members = parseDelimitedList(24 /* JSDocRecordMembers */, parseJSDocRecordMember); checkForTrailingComma(result.members); @@ -11674,7 +11970,7 @@ var ts; return finishNode(result); } function parseJSDocRecordMember() { - var result = createNode(258 /* JSDocRecordMember */); + var result = createNode(260 /* JSDocRecordMember */); result.name = parseSimplePropertyName(); if (token === 54 /* ColonToken */) { nextToken(); @@ -11683,13 +11979,13 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(256 /* JSDocNonNullableType */); + var result = createNode(258 /* JSDocNonNullableType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(254 /* JSDocTupleType */); + var result = createNode(256 /* JSDocTupleType */); nextToken(); result.types = parseDelimitedList(25 /* JSDocTupleTypes */, parseJSDocType); checkForTrailingComma(result.types); @@ -11703,7 +11999,7 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(253 /* JSDocUnionType */); + var result = createNode(255 /* JSDocUnionType */); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); parseExpected(18 /* CloseParenToken */); @@ -11721,7 +12017,7 @@ var ts; return types; } function parseJSDocAllType() { - var result = createNode(250 /* JSDocAllType */); + var result = createNode(252 /* JSDocAllType */); nextToken(); return finishNode(result); } @@ -11744,11 +12040,11 @@ var ts; token === 27 /* GreaterThanToken */ || token === 56 /* EqualsToken */ || token === 47 /* BarToken */) { - var result = createNode(251 /* JSDocUnknownType */, pos); + var result = createNode(253 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(255 /* JSDocNullableType */, pos); + var result = createNode(257 /* JSDocNullableType */, pos); result.type = parseJSDocType(); return finishNode(result); } @@ -11836,7 +12132,7 @@ var ts; if (!tags) { return undefined; } - var result = createNode(265 /* JSDocComment */, start); + var result = createNode(267 /* JSDocComment */, start); result.tags = tags; return finishNode(result, end); } @@ -11873,7 +12169,7 @@ var ts; return undefined; } function handleUnknownTag(atToken, tagName) { - var result = createNode(266 /* JSDocTag */, atToken.pos); + var result = createNode(268 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result, pos); @@ -11924,7 +12220,7 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(267 /* JSDocParameterTag */, atToken.pos); + var result = createNode(269 /* JSDocParameterTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; @@ -11934,27 +12230,27 @@ var ts; return finishNode(result, pos); } function handleReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 268 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 270 /* JSDocReturnTag */; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(268 /* JSDocReturnTag */, atToken.pos); + var result = createNode(270 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result, pos); } function handleTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 269 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 271 /* JSDocTypeTag */; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(269 /* JSDocTypeTag */, atToken.pos); + var result = createNode(271 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result, pos); } function handleTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 270 /* JSDocTemplateTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 272 /* JSDocTemplateTag */; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } var typeParameters = []; @@ -11978,7 +12274,7 @@ var ts; pos++; } typeParameters.end = pos; - var result = createNode(270 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(272 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; @@ -12019,7 +12315,7 @@ var ts; if (sourceFile.statements.length === 0) { // If we don't have any statements in the current source file, then there's no real // way to incrementally parse. So just do a full parse instead. - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setNodeParents*/ true); + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true); } // Make sure we're not trying to incrementally update a source file more than once. Once // we do an update the original source file is considered unusbale from that point onwards. @@ -12075,7 +12371,7 @@ var ts; // inconsistent tree. Setting the parents on the new tree should be very fast. We // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true); + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true); return result; } IncrementalParser.updateSourceFile = updateSourceFile; @@ -12508,16 +12804,16 @@ var ts; function getModuleInstanceState(node) { // A module is uninstantiated if it contains only // 1. interface declarations, type alias declarations - if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 216 /* TypeAliasDeclaration */) { + if (node.kind === 217 /* InterfaceDeclaration */ || node.kind === 218 /* TypeAliasDeclaration */) { return 0 /* NonInstantiated */; } else if (ts.isConstEnumDeclaration(node)) { return 2 /* ConstEnumOnly */; } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) { + else if ((node.kind === 224 /* ImportDeclaration */ || node.kind === 223 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) { return 0 /* NonInstantiated */; } - else if (node.kind === 219 /* ModuleBlock */) { + else if (node.kind === 221 /* ModuleBlock */) { var state = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -12536,7 +12832,7 @@ var ts; }); return state; } - else if (node.kind === 218 /* ModuleDeclaration */) { + else if (node.kind === 220 /* ModuleDeclaration */) { return getModuleInstanceState(node.body); } else { @@ -12604,6 +12900,8 @@ var ts; file.symbolCount = symbolCount; file.classifiableNames = classifiableNames; } + file = undefined; + options = undefined; parent = undefined; container = undefined; blockScopeContainer = undefined; @@ -12632,20 +12930,25 @@ var ts; if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { symbol.members = {}; } - if (symbolFlags & 107455 /* Value */ && !symbol.valueDeclaration) { - symbol.valueDeclaration = node; + if (symbolFlags & 107455 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 220 /* ModuleDeclaration */)) { + // other kinds of value declarations take precedence over modules + symbol.valueDeclaration = node; + } } } // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { if (node.name) { - if (node.kind === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { + if (node.kind === 220 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { return "\"" + node.name.text + "\""; } if (node.name.kind === 136 /* ComputedPropertyName */) { var nameExpression = node.name.expression; - // treat computed property names where expression is string/numeric literal as just string/numeric literal + // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression.kind)) { return nameExpression.text; } @@ -12665,15 +12968,27 @@ var ts; return "__new"; case 149 /* IndexSignature */: return "__index"; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return "__export"; - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return node.isExportEquals ? "export=" : "default"; - case 181 /* BinaryExpression */: - // Binary expression case is for JS module 'module.exports = expr' - return "export="; - case 213 /* FunctionDeclaration */: - case 214 /* ClassDeclaration */: + case 183 /* BinaryExpression */: + switch (ts.getSpecialPropertyAssignmentKind(node)) { + case 2 /* ModuleExports */: + // module.exports = ... + return "export="; + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + // exports.x = ... or this.y = ... + return node.left.name.text; + case 3 /* PrototypeProperty */: + // className.prototype.methodName = ... + return node.left.expression.name.text; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 215 /* FunctionDeclaration */: + case 216 /* ClassDeclaration */: return node.flags & 512 /* Default */ ? "default" : undefined; } } @@ -12750,7 +13065,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedNodeFlags(node) & 2 /* Export */; if (symbolFlags & 8388608 /* Alias */) { - if (node.kind === 230 /* ExportSpecifier */ || (node.kind === 221 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 232 /* ExportSpecifier */ || (node.kind === 223 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -12833,10 +13148,10 @@ var ts; var flags = node.flags; // reset all reachability check related flags on node (for incremental scenarios) flags &= ~1572864 /* ReachabilityCheckFlags */; - if (kind === 215 /* InterfaceDeclaration */) { + if (kind === 217 /* InterfaceDeclaration */) { seenThisKeyword = false; } - var saveState = kind === 248 /* SourceFile */ || kind === 219 /* ModuleBlock */ || ts.isFunctionLikeKind(kind); + var saveState = kind === 250 /* SourceFile */ || kind === 221 /* ModuleBlock */ || ts.isFunctionLikeKind(kind); if (saveState) { savedReachabilityState = currentReachabilityState; savedLabelStack = labelStack; @@ -12854,7 +13169,7 @@ var ts; flags |= 1048576 /* HasExplicitReturn */; } } - if (kind === 215 /* InterfaceDeclaration */) { + if (kind === 217 /* InterfaceDeclaration */) { flags = seenThisKeyword ? flags | 262144 /* ContainsThis */ : flags & ~262144 /* ContainsThis */; } node.flags = flags; @@ -12879,40 +13194,40 @@ var ts; return; } switch (node.kind) { - case 198 /* WhileStatement */: + case 200 /* WhileStatement */: bindWhileStatement(node); break; - case 197 /* DoStatement */: + case 199 /* DoStatement */: bindDoStatement(node); break; - case 199 /* ForStatement */: + case 201 /* ForStatement */: bindForStatement(node); break; - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 196 /* IfStatement */: + case 198 /* IfStatement */: bindIfStatement(node); break; - case 204 /* ReturnStatement */: - case 208 /* ThrowStatement */: + case 206 /* ReturnStatement */: + case 210 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: + case 205 /* BreakStatement */: + case 204 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 209 /* TryStatement */: + case 211 /* TryStatement */: bindTryStatement(node); break; - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: bindSwitchStatement(node); break; - case 220 /* CaseBlock */: + case 222 /* CaseBlock */: bindCaseBlock(node); break; - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: bindLabeledStatement(node); break; default: @@ -12964,7 +13279,7 @@ var ts; popImplicitLabel(postStatementLabel, preStatementState); } function bindIfStatement(n) { - // denotes reachability state when entering 'thenStatement' part of the if statement: + // denotes reachability state when entering 'thenStatement' part of the if statement: // i.e. if condition is false then thenStatement is unreachable var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; // denotes reachability state when entering 'elseStatement': @@ -12987,7 +13302,7 @@ var ts; function bindReturnOrThrow(n) { // bind expression (don't affect reachability) bind(n.expression); - if (n.kind === 204 /* ReturnStatement */) { + if (n.kind === 206 /* ReturnStatement */) { hasExplicitReturn = true; } currentReachabilityState = 4 /* Unreachable */; @@ -12996,7 +13311,7 @@ var ts; // call bind on label (don't affect reachability) bind(n.label); // for continue case touch label so it will be marked a used - var isValidJump = jumpToLabel(n.label, n.kind === 203 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */); + var isValidJump = jumpToLabel(n.label, n.kind === 205 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */); if (isValidJump) { currentReachabilityState = 4 /* Unreachable */; } @@ -13022,7 +13337,7 @@ var ts; // bind expression (don't affect reachability) bind(n.expression); bind(n.caseBlock); - var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242 /* DefaultClause */; }); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 244 /* DefaultClause */; }); // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState; popImplicitLabel(postSwitchLabel, postSwitchState); @@ -13049,37 +13364,37 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: + case 188 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: case 155 /* TypeLiteral */: - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return 1 /* IsContainer */; case 147 /* CallSignature */: case 148 /* ConstructSignature */: case 149 /* IndexSignature */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 152 /* FunctionType */: case 153 /* ConstructorType */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 218 /* ModuleDeclaration */: - case 248 /* SourceFile */: - case 216 /* TypeAliasDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 220 /* ModuleDeclaration */: + case 250 /* SourceFile */: + case 218 /* TypeAliasDeclaration */: return 5 /* IsContainerWithLocals */; - case 244 /* CatchClause */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 220 /* CaseBlock */: + case 246 /* CatchClause */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 222 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 192 /* Block */: + case 194 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Othewise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -13116,18 +13431,18 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 248 /* SourceFile */: + case 250 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 216 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case 155 /* TypeLiteral */: - case 165 /* ObjectLiteralExpression */: - case 215 /* InterfaceDeclaration */: + case 167 /* ObjectLiteralExpression */: + case 217 /* InterfaceDeclaration */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the @@ -13144,10 +13459,10 @@ var ts; case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 216 /* TypeAliasDeclaration */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 218 /* TypeAliasDeclaration */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -13168,11 +13483,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 248 /* SourceFile */ ? node : node.body; - if (body.kind === 248 /* SourceFile */ || body.kind === 219 /* ModuleBlock */) { + var body = node.kind === 250 /* SourceFile */ ? node : node.body; + if (body.kind === 250 /* SourceFile */ || body.kind === 221 /* ModuleBlock */) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 228 /* ExportDeclaration */ || stat.kind === 227 /* ExportAssignment */) { + if (stat.kind === 230 /* ExportDeclaration */ || stat.kind === 229 /* ExportAssignment */) { return true; } } @@ -13256,7 +13571,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */ || prop.kind === 143 /* MethodDeclaration */ + var currentKind = prop.kind === 247 /* PropertyAssignment */ || prop.kind === 248 /* ShorthandPropertyAssignment */ || prop.kind === 143 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen[identifier.text]; @@ -13278,10 +13593,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 248 /* SourceFile */: + case 250 /* SourceFile */: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -13441,17 +13756,17 @@ var ts; } function updateStrictMode(node) { switch (node.kind) { - case 248 /* SourceFile */: - case 219 /* ModuleBlock */: + case 250 /* SourceFile */: + case 221 /* ModuleBlock */: updateStrictModeStatementList(node.statements); return; - case 192 /* Block */: + case 194 /* Block */: if (ts.isFunctionLike(node.parent)) { updateStrictModeStatementList(node.statements); } return; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return; @@ -13481,45 +13796,61 @@ var ts; /* Strict mode checks */ case 69 /* Identifier */: return checkStrictModeIdentifier(node); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: if (ts.isInJavaScriptFile(node)) { - if (ts.isExportsPropertyAssignment(node)) { - bindExportsPropertyAssignment(node); - } - else if (ts.isModuleExportsAssignment(node)) { - bindModuleExportsAssignment(node); + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); } } return checkStrictModeBinaryExpression(node); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return checkStrictModeCatchClause(node); - case 175 /* DeleteExpression */: + case 177 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 180 /* PostfixUnaryExpression */: + case 182 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 205 /* WithStatement */: + case 207 /* WithStatement */: return checkStrictModeWithStatement(node); - case 97 /* ThisKeyword */: + case 161 /* ThisType */: seenThisKeyword = true; return; + case 150 /* TypePredicate */: + return checkTypePredicate(node); case 137 /* TypeParameter */: return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); case 138 /* Parameter */: return bindParameter(node); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: return bindVariableDeclarationOrBindingElement(node); case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); - case 245 /* PropertyAssignment */: - case 246 /* ShorthandPropertyAssignment */: + case 247 /* PropertyAssignment */: + case 248 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); - case 247 /* EnumMember */: + case 249 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); case 147 /* CallSignature */: case 148 /* ConstructSignature */: @@ -13532,7 +13863,7 @@ var ts; // so that it will conflict with any other object literal members with the same // name. return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */); - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: checkStrictModeFunctionName(node); return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); case 144 /* Constructor */: @@ -13546,46 +13877,56 @@ var ts; return bindFunctionOrConstructorType(node); case 155 /* TypeLiteral */: return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: checkStrictModeFunctionName(node); var bindingName = node.name ? node.name.text : "__function"; return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); - case 168 /* CallExpression */: + case 170 /* CallExpression */: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 216 /* ClassDeclaration */: return bindClassLikeDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); - case 216 /* TypeAliasDeclaration */: + case 218 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Imports and exports - case 221 /* ImportEqualsDeclaration */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 223 /* ImportEqualsDeclaration */: + case 226 /* NamespaceImport */: + case 228 /* ImportSpecifier */: + case 232 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - case 223 /* ImportClause */: + case 225 /* ImportClause */: return bindImportClause(node); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return bindExportDeclaration(node); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return bindExportAssignment(node); - case 248 /* SourceFile */: + case 250 /* SourceFile */: return bindSourceFileIfExternalModule(); } } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 69 /* Identifier */) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 161 /* ThisType */) { + seenThisKeyword = true; + } + bind(type); + } function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (ts.isExternalModule(file)) { @@ -13596,7 +13937,7 @@ var ts; bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { - var boundExpression = node.kind === 227 /* ExportAssignment */ ? node.expression : node.right; + var boundExpression = node.kind === 229 /* 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)); @@ -13642,6 +13983,29 @@ var ts; setCommonJsModuleIndicator(node); bindExportAssignment(node); } + function bindThisPropertyAssignment(node) { + // Declare a 'member' in case it turns out the container was an ES5 class + if (container.kind === 175 /* FunctionExpression */ || container.kind === 215 /* FunctionDeclaration */) { + container.symbol.members = container.symbol.members || {}; + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); + } + } + 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. + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classId = node.left.expression.expression; + var funcSymbol = container.locals[classId.text]; + if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */)) { + return; + } + // Set up the members collection if it doesn't exist already + if (!funcSymbol.members) { + funcSymbol.members = {}; + } + // Declare the method/property + declareSymbol(funcSymbol.members, funcSymbol, node.left, 4 /* Property */, 107455 /* PropertyExcludes */); + } function bindCallExpression(node) { // We're only inspecting call expressions to detect CommonJS modules, so we can skip // this check if we've already seen the module indicator @@ -13650,7 +14014,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); } else { @@ -13725,9 +14089,7 @@ var ts; } // If this is a property-parameter, then also declare the property symbol into the // containing class. - if (node.flags & 56 /* AccessibilityModifier */ && - node.parent.kind === 144 /* Constructor */ && - ts.isClassLike(node.parent.parent)) { + if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); } @@ -13797,18 +14159,18 @@ var ts; case 4 /* Unreachable */: var reportError = // report error on all statements except empty ones - (ts.isStatement(node) && node.kind !== 194 /* EmptyStatement */) || + (ts.isStatement(node) && node.kind !== 196 /* EmptyStatement */) || // report error on class declarations - node.kind === 214 /* ClassDeclaration */ || + node.kind === 216 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 218 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 220 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 217 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + (node.kind === 219 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentReachabilityState = 8 /* ReportedUnreachable */; // unreachable code is reported if // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error + // - statement is in not ambient context (statements in ambient context is already an error // so we should not report extras) AND // - node is not variable statement OR // - node is block scoped variable statement OR @@ -13817,7 +14179,7 @@ var ts; // On the other side we do want to report errors on non-initialized 'lets' because of TDZ var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && - (node.kind !== 193 /* VariableStatement */ || + (node.kind !== 195 /* VariableStatement */ || ts.getCombinedNodeFlags(node.declarationList) & 24576 /* BlockScoped */ || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -13853,15 +14215,18 @@ var ts; var nextNodeId = 1; var nextMergeId = 1; function getNodeId(node) { - if (!node.id) - node.id = nextNodeId++; + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } return node.id; } ts.getNodeId = getNodeId; ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { - symbol.id = nextSymbolId++; + symbol.id = nextSymbolId; + nextSymbolId++; } return symbol.id; } @@ -13887,8 +14252,10 @@ var ts; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0 /* ES3 */; var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === 4 /* System */; var emitResolver = createResolver(); var undefinedSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "undefined"); + undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -13902,6 +14269,7 @@ var ts; // The language service will always care about the narrowed type of a symbol, because that is // the type the language says the symbol should have. getTypeOfSymbolAtLocation: getNarrowedTypeOfSymbol, + getSymbolsOfParameterPropertyDeclaration: getSymbolsOfParameterPropertyDeclaration, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: getPropertyOfType, @@ -13918,7 +14286,7 @@ var ts; symbolToString: symbolToString, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: getApparentTypeOfContextualType, + getContextualType: getContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: getResolvedSignature, getConstantValue: getConstantValue, @@ -13943,8 +14311,8 @@ var ts; var undefinedType = createIntrinsicType(32 /* Undefined */ | 2097152 /* ContainsUndefinedOrNull */, "undefined"); var nullType = createIntrinsicType(64 /* Null */ | 2097152 /* ContainsUndefinedOrNull */, "null"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var circularType = createIntrinsicType(1 /* Any */, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyUnionType = emptyObjectType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -13952,8 +14320,8 @@ var ts; // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); var globals = {}; var globalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; @@ -13966,9 +14334,6 @@ var ts; var globalRegExpType; var globalTemplateStringsArrayType; var globalESSymbolType; - var jsxElementType; - /** Lazily loaded, use getJsxIntrinsicElementType() */ - var jsxIntrinsicElementsType; var globalIterableType; var globalIteratorType; var globalIterableIteratorType; @@ -13985,6 +14350,7 @@ var ts; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; var jsxElementClassType; + var deferredNodes; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; @@ -14019,14 +14385,23 @@ var ts; "symbol": { type: esSymbolType, flags: 16777216 /* ESSymbol */ + }, + "undefined": { + type: undefinedType, + flags: 2097152 /* ContainsUndefinedOrNull */ } }; + var jsxElementType; + /** Things we lazy load from the JSX namespace */ + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", ElementClass: "ElementClass", ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - Element: "Element" + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" }; var subtypeRelation = {}; var assignableRelation = {}; @@ -14040,6 +14415,10 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -14095,8 +14474,10 @@ var ts; return result; } function recordMergedSymbol(target, source) { - if (!source.mergeId) - source.mergeId = nextMergeId++; + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { @@ -14121,8 +14502,12 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (!target.valueDeclaration && source.valueDeclaration) + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 220 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 220 /* ModuleDeclaration */))) { + // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; + } ts.forEach(source.declarations, function (node) { target.declarations.push(node); }); @@ -14174,6 +14559,22 @@ 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]; + } + } + } + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } function getSymbolLinks(symbol) { if (symbol.flags & 67108864 /* Transient */) return symbol; @@ -14185,10 +14586,17 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function getSourceFile(node) { - return ts.getAncestor(node, 248 /* SourceFile */); + return ts.getAncestor(node, 250 /* SourceFile */); } function isGlobalSourceFile(node) { - return node.kind === 248 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 250 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + } + /** Is this type one of the apparent types created from the primitive types. */ + function isPrimitiveApparentType(type) { + return type === globalStringType || + type === globalNumberType || + type === globalBooleanType || + type === globalESSymbolType; } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -14207,6 +14615,22 @@ var ts; } // return undefined if we can't find a symbol. } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructoDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructoDeclaration.locals, parameterName, 107455 /* Value */); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); @@ -14221,7 +14645,7 @@ var ts; if (declaration.pos <= usage.pos) { // declaration is before usage // still might be illegal if usage is in the initializer of the variable declaration - return declaration.kind !== 211 /* VariableDeclaration */ || + return declaration.kind !== 213 /* VariableDeclaration */ || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } // declaration is after usage @@ -14229,14 +14653,14 @@ var ts; return isUsedInFunctionOrNonStaticProperty(declaration, usage); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); - if (declaration.parent.parent.kind === 193 /* VariableStatement */ || - declaration.parent.parent.kind === 199 /* ForStatement */) { + if (declaration.parent.parent.kind === 195 /* VariableStatement */ || + declaration.parent.parent.kind === 201 /* ForStatement */) { // variable statement/for statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) return isSameScopeDescendentOf(usage, declaration, container); } - else if (declaration.parent.parent.kind === 201 /* ForOfStatement */ || - declaration.parent.parent.kind === 200 /* ForInStatement */) { + else if (declaration.parent.parent.kind === 203 /* ForOfStatement */ || + declaration.parent.parent.kind === 202 /* ForInStatement */) { // ForIn/ForOf case - use site should not be used in expression part var expression = declaration.parent.parent.expression; return isSameScopeDescendentOf(usage, expression, container); @@ -14277,25 +14701,46 @@ var ts; // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { - // Type parameters of a function are in scope in the entire function declaration, including the parameter - // list and return type. However, local types are only in scope in the function body. - if (!(meaning & 793056 /* Type */) || - !(result.flags & (793056 /* Type */ & ~262144 /* TypeParameter */)) || - !ts.isFunctionLike(location) || - lastLocation === location.body) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + if (meaning & result.flags & 793056 /* Type */) { + useResult = result.flags & 262144 /* TypeParameter */ + ? lastLocation === location.type || + lastLocation.kind === 138 /* Parameter */ || + lastLocation.kind === 137 /* TypeParameter */ + : false; + } + if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 138 /* Parameter */ || + (lastLocation === location.type && + result.valueDeclaration.kind === 138 /* Parameter */); + } + } + if (useResult) { break loop; } - result = undefined; + else { + result = undefined; + } } } switch (location.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 248 /* SourceFile */ || - (location.kind === 218 /* ModuleDeclaration */ && location.name.kind === 9 /* StringLiteral */)) { + if (location.kind === 250 /* SourceFile */ || + (location.kind === 220 /* ModuleDeclaration */ && location.name.kind === 9 /* StringLiteral */)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports["default"]) { @@ -14306,7 +14751,7 @@ var ts; result = undefined; } // Because of module/namespace merging, a module's exports are in scope, - // yet we never want to treat an export specifier as putting a member in scope. + // yet we never want to treat an export specifier as putting a member in scope. // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. // Two things to note about this: // 1. We have to check this without calling getSymbol. The problem with calling getSymbol @@ -14318,7 +14763,7 @@ var ts; // which is not the desired behavior. if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 /* Alias */ && - ts.getDeclarationOfKind(moduleExports[name], 230 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExports[name], 232 /* ExportSpecifier */)) { break; } } @@ -14326,7 +14771,7 @@ var ts; break loop; } break; - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } @@ -14349,9 +14794,9 @@ var ts; } } break; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 217 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { if (lastLocation && lastLocation.flags & 64 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 @@ -14362,7 +14807,7 @@ var ts; } break loop; } - if (location.kind === 186 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 188 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -14380,7 +14825,7 @@ var ts; // case 136 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 215 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 217 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -14393,14 +14838,14 @@ var ts; case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + case 176 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 173 /* FunctionExpression */: + case 175 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -14482,7 +14927,7 @@ var ts; // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 211 /* VariableDeclaration */), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 213 /* VariableDeclaration */), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -14503,10 +14948,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 223 /* ImportEqualsDeclaration */) { return node; } - while (node && node.kind !== 222 /* ImportDeclaration */) { + while (node && node.kind !== 224 /* ImportDeclaration */) { node = node.parent; } return node; @@ -14516,7 +14961,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 232 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 234 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -14525,9 +14970,12 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); - if (!exportDefaultSymbol) { + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveSymbol(moduleSymbol.exports["export="]) || resolveSymbol(moduleSymbol); + } return exportDefaultSymbol; } } @@ -14535,14 +14983,6 @@ var ts; var moduleSpecifier = node.parent.parent.moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } - function getMemberOfModuleVariable(moduleSymbol, name) { - if (moduleSymbol.flags & 3 /* Variable */) { - var typeAnnotation = moduleSymbol.valueDeclaration.type; - if (typeAnnotation) { - return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); - } - } - } // This function creates a synthetic symbol that combines the value side of one symbol with the // type/namespace side of another symbol. Consider this example: // @@ -14623,17 +15063,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node); - case 223 /* ImportClause */: + case 225 /* ImportClause */: return getTargetOfImportClause(node); - case 224 /* NamespaceImport */: + case 226 /* NamespaceImport */: return getTargetOfNamespaceImport(node); - case 226 /* ImportSpecifier */: + case 228 /* ImportSpecifier */: return getTargetOfImportSpecifier(node); - case 230 /* ExportSpecifier */: + case 232 /* ExportSpecifier */: return getTargetOfExportSpecifier(node); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return getTargetOfExportAssignment(node); } } @@ -14678,11 +15118,11 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 227 /* ExportAssignment */) { + if (node.kind === 229 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 230 /* ExportSpecifier */) { + else if (node.kind === 232 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -14695,7 +15135,7 @@ var ts; // This function is only for imports with entity names function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 221 /* ImportEqualsDeclaration */); + importDeclaration = ts.getAncestor(entityName, 223 /* ImportEqualsDeclaration */); ts.Debug.assert(importDeclaration !== undefined); } // There are three things we might try to look for. In the following examples, @@ -14714,7 +15154,7 @@ var ts; else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 221 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 223 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); } } @@ -14734,7 +15174,7 @@ var ts; return undefined; } } - else if (name.kind === 135 /* QualifiedName */ || name.kind === 166 /* PropertyAccessExpression */) { + else if (name.kind === 135 /* QualifiedName */ || name.kind === 168 /* PropertyAccessExpression */) { var left = name.kind === 135 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 135 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors); @@ -14760,16 +15200,12 @@ var ts; return; } var moduleReferenceLiteral = moduleReferenceExpression; - var searchPath = ts.getDirectoryPath(getSourceFile(location).fileName); // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); if (moduleName === undefined) { return; } - if (moduleName.indexOf("!") >= 0) { - moduleName = moduleName.substr(0, moduleName.indexOf("!")); - } var isRelative = ts.isExternalModuleNameRelative(moduleName); if (!isRelative) { var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); @@ -14817,38 +15253,66 @@ var ts; var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } - function extendExportSymbols(target, source) { + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; + if (lookupTable && exportNode) { + lookupTable[id] = { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }; + } + } + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + if (!lookupTable[id].exportsWithDuplicate) { + lookupTable[id].exportsWithDuplicate = [exportNode]; + } + else { + lookupTable[id].exportsWithDuplicate.push(exportNode); + } } } } function getExportsForModule(moduleSymbol) { - var result; var visitedSymbols = []; - visit(moduleSymbol); - return result || moduleSymbol.exports; + return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. function visit(symbol) { - if (symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol)) { - visitedSymbols.push(symbol); - if (symbol !== moduleSymbol) { - if (!result) { - result = cloneSymbolTable(moduleSymbol.exports); - } - extendExportSymbols(result, symbol.exports); - } - // All export * declarations are collected in an __export symbol by the binder - var exportStars = symbol.exports["__export"]; - if (exportStars) { - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - visit(resolveExternalModuleName(node, node.moduleSpecifier)); - } - } + if (!(symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol))) { + return; } + visitedSymbols.push(symbol); + var symbols = cloneSymbolTable(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 = {}; + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node); + } + 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)) { + continue; + } + for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { + var node = exportsWithDuplicate_1[_b]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable[id].specifierText, id)); + } + } + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; } } function getMergedSymbol(symbol) { @@ -14893,7 +15357,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount++; + result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -14956,17 +15421,17 @@ var ts; } } switch (location_1.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -15007,7 +15472,7 @@ var ts; return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 /* Alias */ && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230 /* ExportSpecifier */)) { + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 232 /* ExportSpecifier */)) { if (!useOnlyExternalAliasing || // Is this external alias, then use it to name ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { @@ -15044,7 +15509,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 232 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -15117,8 +15582,8 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 218 /* ModuleDeclaration */ && declaration.name.kind === 9 /* StringLiteral */) || - (declaration.kind === 248 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return (declaration.kind === 220 /* ModuleDeclaration */ && declaration.name.kind === 9 /* StringLiteral */) || + (declaration.kind === 250 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -15158,8 +15623,8 @@ var ts; // Typeof value meaning = 107455 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 135 /* QualifiedName */ || entityName.kind === 166 /* PropertyAccessExpression */ || - entityName.parent.kind === 221 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 135 /* QualifiedName */ || entityName.kind === 168 /* PropertyAccessExpression */ || + entityName.parent.kind === 223 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1536 /* Namespace */; @@ -15193,9 +15658,9 @@ var ts; ts.releaseStringWriter(writer); return result; } - function signatureToString(signature, enclosingDeclaration, flags) { + function signatureToString(signature, enclosingDeclaration, flags, kind) { var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); var result = writer.string(); ts.releaseStringWriter(writer); return result; @@ -15217,7 +15682,7 @@ var ts; while (node.kind === 160 /* ParenthesizedType */) { node = node.parent; } - if (node.kind === 216 /* TypeAliasDeclaration */) { + if (node.kind === 218 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -15231,10 +15696,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: return "(Anonymous class)"; - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return "(Anonymous function)"; } } @@ -15322,10 +15787,16 @@ var ts; function writeType(type, flags) { // Write undefined/null type as any if (type.flags & 16777343 /* 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); + if (type.flags & 134217728 /* PredicateType */) { + buildTypePredicateDisplay(writer, type.predicate); + buildTypeDisplay(type.predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } + else { + // 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 */) { if (inObjectTypeLiteral) { @@ -15381,11 +15852,13 @@ var ts; } if (pos < end) { writePunctuation(writer, 25 /* LessThanToken */); - writeType(typeArguments[pos++], 0 /* None */); + writeType(typeArguments[pos], 0 /* None */); + pos++; while (pos < end) { writePunctuation(writer, 24 /* CommaToken */); writeSpace(writer); - writeType(typeArguments[pos++], 0 /* None */); + writeType(typeArguments[pos], 0 /* None */); + pos++; } writePunctuation(writer, 27 /* GreaterThanToken */); } @@ -15481,7 +15954,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 248 /* SourceFile */ || declaration.parent.kind === 219 /* ModuleBlock */; + return declaration.parent.kind === 250 /* SourceFile */ || declaration.parent.kind === 221 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -15517,7 +15990,7 @@ var ts; if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* OpenParenToken */); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -15529,7 +16002,7 @@ var ts; } writeKeyword(writer, 92 /* NewKeyword */); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -15543,15 +16016,13 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - writeKeyword(writer, 92 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } @@ -15594,7 +16065,7 @@ var ts; if (p.flags & 536870912 /* Optional */) { writePunctuation(writer, 53 /* QuestionToken */); } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } @@ -15682,6 +16153,17 @@ var ts; } writePunctuation(writer, 18 /* CloseParenToken */); } + function buildTypePredicateDisplay(writer, predicate) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 97 /* ThisKeyword */); + } + writeSpace(writer); + writeKeyword(writer, 124 /* IsKeyword */); + writeSpace(writer); + } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8 /* WriteArrowStyleSignature */) { writeSpace(writer); @@ -15691,20 +16173,14 @@ var ts; writePunctuation(writer, 54 /* ColonToken */); } writeSpace(writer); - var returnType; - if (signature.typePredicate) { - writer.writeParameter(signature.typePredicate.parameterName); - writeSpace(writer); - writeKeyword(writer, 124 /* IsKeyword */); - writeSpace(writer); - returnType = signature.typePredicate.type; - } - else { - returnType = getReturnTypeOfSignature(signature); - } + var returnType = getReturnTypeOfSignature(signature); buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1 /* Construct */) { + writeKeyword(writer, 92 /* NewKeyword */); + writeSpace(writer); + } if (signature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */)) { // Instantiated signature, write type arguments instead // This is achieved by passing in the mapper separately @@ -15729,82 +16205,36 @@ var ts; }); } function isDeclarationVisible(node) { - function getContainingExternalModule(node) { - for (; node; node = node.parent) { - if (node.kind === 218 /* ModuleDeclaration */) { - if (node.name.kind === 9 /* StringLiteral */) { - return node; - } - } - else if (node.kind === 248 /* SourceFile */) { - return ts.isExternalOrCommonJsModule(node) ? node : undefined; - } - } - ts.Debug.fail("getContainingModule cant reach here"); - } - function isUsedInExportAssignment(node) { - // Get source File and see if it is external module and has export assigned symbol - var externalModule = getContainingExternalModule(node); - var exportAssignmentSymbol; - var resolvedExportSymbol; - if (externalModule) { - // This is export assigned symbol node - var externalModuleSymbol = getSymbolOfNode(externalModule); - exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); - var symbolOfNode = getSymbolOfNode(node); - if (isSymbolUsedInExportAssignment(symbolOfNode)) { - return true; - } - // if symbolOfNode is alias declaration, resolve the symbol declaration and check - if (symbolOfNode.flags & 8388608 /* Alias */) { - return isSymbolUsedInExportAssignment(resolveAlias(symbolOfNode)); - } - } - // Check if the symbol is used in export assignment - function isSymbolUsedInExportAssignment(symbol) { - if (exportAssignmentSymbol === symbol) { - return true; - } - if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 8388608 /* Alias */)) { - // if export assigned symbol is alias declaration, resolve the alias - resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol); - if (resolvedExportSymbol === symbol) { - return true; - } - // Container of resolvedExportSymbol is visible - return ts.forEach(resolvedExportSymbol.declarations, function (current) { - while (current) { - if (current === node) { - return true; - } - current = current.parent; - } - }); - } + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); } + return links.isVisible; } + return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 163 /* BindingElement */: + case 165 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // Otherwise fall through - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 213 /* FunctionDeclaration */: - case 217 /* EnumDeclaration */: - case 221 /* ImportEqualsDeclaration */: + case 220 /* ModuleDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 215 /* FunctionDeclaration */: + case 219 /* EnumDeclaration */: + case 223 /* ImportEqualsDeclaration */: var parent_4 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedNodeFlags(node) & 2 /* Export */) && - !(node.kind !== 221 /* ImportEqualsDeclaration */ && parent_4.kind !== 248 /* SourceFile */ && ts.isInAmbientContext(parent_4))) { + !(node.kind !== 223 /* ImportEqualsDeclaration */ && parent_4.kind !== 250 /* SourceFile */ && ts.isInAmbientContext(parent_4))) { return isGlobalSourceFile(parent_4); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible @@ -15825,7 +16255,7 @@ var ts; case 147 /* CallSignature */: case 149 /* IndexSignature */: case 138 /* Parameter */: - case 219 /* ModuleBlock */: + case 221 /* ModuleBlock */: case 152 /* FunctionType */: case 153 /* ConstructorType */: case 155 /* TypeLiteral */: @@ -15838,36 +16268,29 @@ var ts; return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: + case 225 /* ImportClause */: + case 226 /* NamespaceImport */: + case 228 /* ImportSpecifier */: return false; // Type parameters are always visible case 137 /* TypeParameter */: // Source file is always visible - case 248 /* SourceFile */: + case 250 /* SourceFile */: return true; // Export assignments do not create name bindings outside the module - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return false; default: ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); } } - if (node) { - var links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 227 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 229 /* ExportAssignment */) { exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 230 /* ExportSpecifier */) { + else if (node.parent.kind === 232 /* ExportSpecifier */) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -15917,7 +16340,7 @@ var ts; return false; } resolutionTargets.push(target); - resolutionResults.push(true); + resolutionResults.push(/*items*/ true); resolutionPropertyNames.push(propertyName); return true; } @@ -15959,7 +16382,7 @@ var ts; node = ts.getRootDeclaration(node); // Parent chain: // VaribleDeclaration -> VariableDeclarationList -> VariableStatement -> 'Declaration Container' - return node.kind === 211 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; + return node.kind === 213 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; } function getTypeOfPrototypeProperty(prototype) { // TypeScript 1.0 spec (April 2014): 8.4 @@ -16018,7 +16441,7 @@ var ts; return parentType; } var type; - if (pattern.kind === 161 /* ObjectBindingPattern */) { + if (pattern.kind === 163 /* ObjectBindingPattern */) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name_10 = declaration.propertyName || declaration.name; if (isComputedNonLiteralName(name_10)) { @@ -16067,10 +16490,10 @@ var ts; // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration) { // A variable declared in a for..in statement is always of type any - if (declaration.parent.parent.kind === 200 /* ForInStatement */) { + if (declaration.parent.parent.kind === 202 /* ForInStatement */) { return anyType; } - if (declaration.parent.parent.kind === 201 /* ForOfStatement */) { + if (declaration.parent.parent.kind === 203 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -16104,7 +16527,7 @@ var ts; return checkExpressionCached(declaration.initializer); } // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 246 /* ShorthandPropertyAssignment */) { + if (declaration.kind === 248 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } // If the declaration specifies a binding pattern, use the type implied by the binding pattern @@ -16160,7 +16583,7 @@ var ts; 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 === 187 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return e.kind === 189 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { var result = createNewTupleType(elementTypes); result.pattern = pattern; @@ -16176,7 +16599,7 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType) { - return pattern.kind === 161 /* ObjectBindingPattern */ + return pattern.kind === 163 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType) : getTypeFromArrayBindingPattern(pattern, includePatternInType); } @@ -16198,7 +16621,13 @@ var ts; // During a normal type check we'll never get to here with a property assignment (the check of the containing // object literal uses a different path). We exclude widening only so that language services and type verification // tools see the actual type. - return declaration.kind !== 245 /* PropertyAssignment */ ? getWidenedType(type) : type; + if (declaration.kind === 247 /* PropertyAssignment */) { + return type; + } + if (type.flags & 134217728 /* PredicateType */ && (declaration.kind === 141 /* PropertyDeclaration */ || declaration.kind === 140 /* PropertySignature */)) { + return type; + } + return getWidenedType(type); } // Rest parameters default to type any[], other parameters default to type any type = declaration.dotDotDotToken ? anyArrayType : anyType; @@ -16220,20 +16649,24 @@ var ts; } // Handle catch clause variables var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 244 /* CatchClause */) { + if (declaration.parent.kind === 246 /* CatchClause */) { return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 227 /* ExportAssignment */) { + if (declaration.kind === 229 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } // Handle module.exports = expr - if (declaration.kind === 181 /* BinaryExpression */) { + if (declaration.kind === 183 /* BinaryExpression */) { return links.type = checkExpression(declaration.right); } - // Handle exports.p = expr - if (declaration.kind === 166 /* PropertyAccessExpression */) { - return checkExpressionCached(declaration.parent.right); + if (declaration.kind === 168 /* PropertyAccessExpression */) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === 183 /* BinaryExpression */) { + // Handle exports.p = expr or this.p = expr or className.prototype.method = expr + return links.type = checkExpressionCached(declaration.parent.right); + } } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { @@ -16406,9 +16839,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 214 /* ClassDeclaration */ || node.kind === 186 /* ClassExpression */ || - node.kind === 213 /* FunctionDeclaration */ || node.kind === 173 /* FunctionExpression */ || - node.kind === 143 /* MethodDeclaration */ || node.kind === 174 /* ArrowFunction */) { + if (node.kind === 216 /* ClassDeclaration */ || node.kind === 188 /* ClassExpression */ || + node.kind === 215 /* FunctionDeclaration */ || node.kind === 175 /* FunctionExpression */ || + node.kind === 143 /* MethodDeclaration */ || node.kind === 176 /* ArrowFunction */) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -16418,7 +16851,7 @@ var ts; } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 215 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 217 /* InterfaceDeclaration */); return appendOuterTypeParameters(undefined, declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -16427,8 +16860,8 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 214 /* ClassDeclaration */ || - node.kind === 186 /* ClassExpression */ || node.kind === 216 /* TypeAliasDeclaration */) { + if (node.kind === 217 /* InterfaceDeclaration */ || node.kind === 216 /* ClassDeclaration */ || + node.kind === 188 /* ClassExpression */ || node.kind === 218 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -16492,9 +16925,6 @@ var ts; } return type.resolvedBaseConstructorType; } - function hasClassBaseType(type) { - return !!ts.forEach(getBaseTypes(type), function (t) { return !!(t.symbol.flags & 32 /* Class */); }); - } function getBaseTypes(type) { var isClass = type.symbol.flags & 32 /* Class */; var isInterface = type.symbol.flags & 64 /* Interface */; @@ -16571,7 +17001,7 @@ var ts; type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 217 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -16603,7 +17033,7 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 /* InterfaceDeclaration */) { + if (declaration.kind === 217 /* InterfaceDeclaration */) { if (declaration.flags & 262144 /* ContainsThis */) { return false; } @@ -16659,7 +17089,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 216 /* TypeAliasDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 218 /* TypeAliasDeclaration */); var type = getTypeFromTypeNode(declaration.type); if (popTypeResolution()) { links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -16748,7 +17178,7 @@ var ts; case 120 /* BooleanKeyword */: case 131 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 9 /* StringLiteral */: + case 162 /* StringLiteralType */: return true; case 156 /* ArrayType */: return isIndependentType(node.elementType); @@ -16824,14 +17254,6 @@ var ts; } } } - function addInheritedSignatures(signatures, baseSignatures) { - if (baseSignatures) { - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var signature = baseSignatures_1[_i]; - signatures.push(signature); - } - } - } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; @@ -16892,33 +17314,32 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, parameters, resolvedReturnType, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - if (!hasClassBaseType(classType)) { - return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; + } var baseTypeNode = getBaseTypeNodeOfClass(classType); var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { - var baseSig = baseSignatures_2[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -16949,7 +17370,7 @@ var ts; function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreReturnTypes, compareTypesIdentical)) { return s; } } @@ -17052,36 +17473,29 @@ var ts; } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; - var members; - var callSignatures; - var constructSignatures; - var stringIndexType; - var numberIndexType; if (type.target) { - members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); - callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); - constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); - stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0 /* String */), type.mapper); - numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1 /* Number */), type.mapper); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); + var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); + var stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0 /* String */), type.mapper); + var numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1 /* Number */), type.mapper); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } else if (symbol.flags & 2048 /* TypeLiteral */) { - members = symbol.members; - callSignatures = getSignaturesOfSymbol(members["__call"]); - constructSignatures = getSignaturesOfSymbol(members["__new"]); - stringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); - numberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members["__call"]); + var constructSignatures = getSignaturesOfSymbol(members["__new"]); + var stringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); + var numberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } else { // Combinations of function, class, enum and module - members = emptySymbols; - callSignatures = emptyArray; - constructSignatures = emptyArray; + var members = emptySymbols; + var constructSignatures = emptyArray; if (symbol.flags & 1952 /* HasExports */) { members = getExportsOfSymbol(symbol); } - if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { - callSignatures = getSignaturesOfSymbol(symbol); - } if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); @@ -17094,10 +17508,16 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } - stringIndexType = undefined; - numberIndexType = (symbol.flags & 384 /* Enum */) ? stringType : undefined; + var numberIndexType = (symbol.flags & 384 /* Enum */) ? stringType : undefined; + setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexType); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -17122,15 +17542,15 @@ var ts; } return type; } - // Return properties of an object type or an empty array for other types + /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { if (type.flags & 80896 /* ObjectType */) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } - // 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. + /** 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 */) { var resolved = resolveStructuredTypeMembers(type); @@ -17201,12 +17621,15 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { 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 */; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 /* Private */ | 32 /* Protected */))) { + commonFlags &= prop.flags; if (!props) { props = [prop]; } @@ -17235,7 +17658,10 @@ var ts; } propTypes.push(getTypeOfSymbol(prop)); } - var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */, name); + var result = createSymbol(4 /* Property */ | + 67108864 /* Transient */ | + 268435456 /* SyntheticProperty */ | + commonFlags, name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & 16384 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -17292,22 +17718,6 @@ var ts; function getSignaturesOfType(type, kind) { return getSignaturesOfStructuredType(getApparentType(type), kind); } - function typeHasConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & (80896 /* ObjectType */ | 16384 /* Union */)) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.constructSignatures.length > 0; - } - return false; - } - function typeHasCallOrConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & 130048 /* StructuredType */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; - } - return false; - } function getIndexTypeOfStructuredType(type, kind) { if (type.flags & 130048 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); @@ -17353,6 +17763,23 @@ var ts; } return false; } + function createTypePredicateFromTypePredicateNode(node) { + if (node.parameterName.kind === 69 /* Identifier */) { + var parameterName = node.parameterName; + return { + kind: 1 /* Identifier */, + parameterName: parameterName ? parameterName.text : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0 /* This */, + type: getTypeFromTypeNode(node.type) + }; + } + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { @@ -17366,8 +17793,14 @@ var ts; var minArgumentCount = -1; for (var i = 0, n = declaration.parameters.length; i < n; i++) { var param = declaration.parameters[i]; - parameters.push(param.symbol); - if (param.type && param.type.kind === 9 /* StringLiteral */) { + var paramSymbol = param.symbol; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.name, 107455 /* Value */, undefined, undefined); + paramSymbol = resolvedSymbol; + } + parameters.push(paramSymbol); + if (param.type && param.type.kind === 162 /* StringLiteralType */) { hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken) { @@ -17384,20 +17817,11 @@ var ts; minArgumentCount = declaration.parameters.length; } var returnType; - var typePredicate; if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); - if (declaration.type.kind === 150 /* TypePredicate */) { - var typePredicateNode = declaration.type; - typePredicate = { - parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, - parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, - type: getTypeFromTypeNode(typePredicateNode.type) - }; - } } else { // TypeScript 1.0 spec (April 2014): @@ -17410,7 +17834,7 @@ var ts; returnType = anyType; } } - links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -17423,7 +17847,7 @@ var ts; switch (node.kind) { case 152 /* FunctionType */: case 153 /* ConstructorType */: - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 144 /* Constructor */: @@ -17432,8 +17856,8 @@ var ts; case 149 /* IndexSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: // Don't include signature if node is the implementation of an overloaded function. A node is considered // an implementation node if it has a body and the previous node is of the same kind and immediately // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). @@ -17499,7 +17923,7 @@ var ts; return anyType; } function getSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } function getErasedSignature(signature) { if (!signature.typeParameters) @@ -17509,7 +17933,7 @@ var ts; signature.erasedSignatureCache = instantiateSignature(getErasedSignature(signature.target), signature.mapper); } else { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); } } return signature.erasedSignatureCache; @@ -17556,17 +17980,38 @@ var ts; ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType : undefined; } - function getConstraintOfTypeParameter(type) { - if (!type.constraint) { - if (type.target) { - var targetConstraint = getConstraintOfTypeParameter(type.target); - type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 137 /* TypeParameter */).constraint; + } + function hasConstraintReferenceTo(type, target) { + var checked; + while (type && type.flags & 512 /* TypeParameter */ && !ts.contains(checked, type)) { + if (type === target) { + return true; + } + (checked || (checked = [])).push(type); + var constraintDeclaration = getConstraintDeclaration(type); + type = constraintDeclaration && getTypeFromTypeNode(constraintDeclaration); + } + return false; + } + function getConstraintOfTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 137 /* TypeParameter */).constraint); + var constraintDeclaration = getConstraintDeclaration(typeParameter); + var constraint = getTypeFromTypeNode(constraintDeclaration); + if (hasConstraintReferenceTo(constraint, typeParameter)) { + error(constraintDeclaration, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + constraint = unknownType; + } + typeParameter.constraint = constraint; } } - return type.constraint === noConstraintType ? undefined : type.constraint; + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 137 /* TypeParameter */).parent); @@ -17614,50 +18059,6 @@ var ts; } return type; } - function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode, typeParameterSymbol) { - var links = getNodeLinks(typeReferenceNode); - if (links.isIllegalTypeReferenceInConstraint !== undefined) { - return links.isIllegalTypeReferenceInConstraint; - } - // bubble up to the declaration - var currentNode = typeReferenceNode; - // forEach === exists - while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { - currentNode = currentNode.parent; - } - // if last step was made from the type parameter this means that path has started somewhere in constraint which is illegal - links.isIllegalTypeReferenceInConstraint = currentNode.kind === 137 /* TypeParameter */; - return links.isIllegalTypeReferenceInConstraint; - } - function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { - var typeParameterSymbol; - function check(n) { - if (n.kind === 151 /* TypeReference */ && n.typeName.kind === 69 /* Identifier */) { - var links = getNodeLinks(n); - if (links.isIllegalTypeReferenceInConstraint === undefined) { - var symbol = resolveName(typeParameter, n.typeName.text, 793056 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - if (symbol && (symbol.flags & 262144 /* TypeParameter */)) { - // TypeScript 1.0 spec (April 2014): 3.4.1 - // Type parameters declared in a particular type parameter list - // may not be referenced in constraints in that type parameter list - // symbol.declaration.parent === typeParameter.parent - // -> typeParameter and symbol.declaration originate from the same type parameter list - // -> illegal for all declarations in symbol - // forEach === exists - links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent === typeParameter.parent; }); - } - } - if (links.isIllegalTypeReferenceInConstraint) { - error(typeParameter, ts.Diagnostics.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); - } - } - ts.forEachChild(n, check); - } - if (typeParameter.constraint) { - typeParameterSymbol = getSymbolOfNode(typeParameter); - check(typeParameter.constraint); - } - } // Get type from reference to class or interface function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(symbol); @@ -17702,13 +18103,6 @@ var ts; } // Get type from reference to named type that cannot be generic (enum or type parameter) function getTypeFromNonGenericTypeReference(node, symbol) { - if (symbol.flags & 262144 /* TypeParameter */ && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { - // TypeScript 1.0 spec (April 2014): 3.4.1 - // Type parameters declared in a particular type parameter list - // may not be referenced in constraints in that type parameter list - // Implementation: such type references are resolved to 'unknown' type that usually denotes error - return unknownType; - } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); return unknownType; @@ -17751,9 +18145,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: return declaration; } } @@ -17785,10 +18179,6 @@ var ts; if (arity === void 0) { arity = 0; } return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } - function tryGetGlobalType(name, arity) { - if (arity === void 0) { arity = 0; } - return getTypeOfGlobalSymbol(getGlobalSymbol(name, 793056 /* Type */, /*diagnostic*/ undefined), arity); - } /** * Returns a type that is inside a namespace at the global scope, e.g. * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type @@ -17908,7 +18298,7 @@ var ts; // a named type that circularly references itself. function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { - return emptyObjectType; + return emptyUnionType; } var typeSet = []; addTypesToSet(typeSet, types, 16384 /* Union */); @@ -17980,8 +18370,7 @@ var ts; } return links.resolvedType; } - function getStringLiteralType(node) { - var text = node.text; + function getStringLiteralTypeForText(text) { if (ts.hasProperty(stringLiteralTypes, text)) { return stringLiteralTypes[text]; } @@ -17989,17 +18378,17 @@ var ts; type.text = text; return type; } - function getTypeFromStringLiteral(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralType(node); + links.resolvedType = getStringLiteralTypeForText(node.text); } return links.resolvedType; } function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 215 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 217 /* InterfaceDeclaration */)) { if (!(container.flags & 64 /* Static */) && (container.kind !== 144 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -18015,6 +18404,22 @@ var ts; } return links.resolvedType; } + function getPredicateType(node) { + return createPredicateType(getSymbolOfNode(node), createTypePredicateFromTypePredicateNode(node)); + } + function createPredicateType(symbol, predicate) { + var type = createType(8 /* Boolean */ | 134217728 /* PredicateType */); + type.symbol = symbol; + type.predicate = predicate; + return type; + } + function getTypeFromPredicateTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getPredicateType(node); + } + return links.resolvedType; + } function getTypeFromTypeNode(node) { switch (node.kind) { case 117 /* AnyKeyword */: @@ -18029,15 +18434,15 @@ var ts; return esSymbolType; case 103 /* VoidKeyword */: return voidType; - case 97 /* ThisKeyword */: + case 161 /* ThisType */: return getTypeFromThisTypeNode(node); - case 9 /* StringLiteral */: - return getTypeFromStringLiteral(node); + case 162 /* StringLiteralType */: + return getTypeFromStringLiteralTypeNode(node); case 151 /* TypeReference */: return getTypeFromTypeReference(node); case 150 /* TypePredicate */: - return booleanType; - case 188 /* ExpressionWithTypeArguments */: + return getTypeFromPredicateTypeNode(node); + case 190 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); case 154 /* TypeQuery */: return getTypeFromTypeQueryNode(node); @@ -18117,18 +18522,22 @@ var ts; return t; }; } - function createInferenceMapper(context) { - var mapper = function (t) { - for (var i = 0; i < context.typeParameters.length; i++) { - if (t === context.typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); + function getInferenceMapper(context) { + if (!context.mapper) { + var mapper = function (t) { + var typeParameters = context.typeParameters; + for (var i = 0; i < typeParameters.length; i++) { + if (t === typeParameters[i]) { + context.inferences[i].isFixed = true; + return getInferredType(context, i); + } } - } - return t; - }; - mapper.context = context; - return mapper; + return t; + }; + mapper.context = context; + context.mapper = mapper; + } + return context.mapper; } function identityMapper(type) { return type; @@ -18136,33 +18545,42 @@ var ts; function combineTypeMappers(mapper1, mapper2) { return function (t) { return instantiateType(mapper1(t), mapper2); }; } - function instantiateTypeParameter(typeParameter, mapper) { + function cloneTypeParameter(typeParameter) { var result = createType(512 /* TypeParameter */); result.symbol = typeParameter.symbol; - if (typeParameter.constraint) { - result.constraint = instantiateType(typeParameter.constraint, mapper); + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; } else { - result.target = typeParameter; - result.mapper = mapper; + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; } - return result; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; - var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } } - if (signature.typePredicate) { - freshTypePredicate = { - parameterName: signature.typePredicate.parameterName, - parameterIndex: signature.typePredicate.parameterIndex, - type: instantiateType(signature.typePredicate.type, mapper) - }; - } - var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -18226,6 +18644,10 @@ var ts; if (type.flags & 32768 /* Intersection */) { return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); } + if (type.flags & 134217728 /* PredicateType */) { + var predicate = type.predicate; + return createPredicateType(type.symbol, cloneTypePredicate(predicate, mapper)); + } } return type; } @@ -18234,25 +18656,25 @@ var ts; function isContextSensitive(node) { ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return isContextSensitiveFunctionLikeDeclaration(node); - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return node.operatorToken.kind === 52 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: return isContextSensitive(node.initializer); case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: return isContextSensitiveFunctionLikeDeclaration(node); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return isContextSensitive(node.expression); } return false; @@ -18278,7 +18700,7 @@ var ts; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); } - function compareTypes(source, target) { + function compareTypesIdentical(source, target) { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; } function isTypeSubtypeOf(source, target) { @@ -18293,10 +18715,84 @@ var ts; function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } - function isSignatureAssignableTo(source, target) { - var sourceType = getOrCreateTypeFromSignature(source); - var targetType = getOrCreateTypeFromSignature(target); - return checkTypeRelatedTo(sourceType, targetType, assignableRelation, /*errorNode*/ undefined); + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return true; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return false; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + for (var i = 0; i < checkCount; i++) { + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + var related = isTypeAssignableTo(t, s) || isTypeAssignableTo(s, t); + if (!related) { + return false; + } + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return true; + } + var sourceReturnType = getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + if (targetReturnType.flags & 134217728 /* PredicateType */ && targetReturnType.predicate.kind === 1 /* Identifier */) { + if (!(sourceReturnType.flags & 134217728 /* PredicateType */)) { + return false; + } + } + return isTypeAssignableTo(sourceReturnType, targetReturnType); + } + return true; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, /*errorNode*/ undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, /*errorNode*/ undefined)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + // If both have rest parameters, get the max and add 1 to + // compensate for the rest parameter. + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + // Return the count for whichever signature doesn't have rest parameters. + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). @@ -18370,6 +18866,11 @@ var ts; 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)) { + return result; + } + } if (source.flags & 256 /* StringLiteral */ && target === stringType) return -1 /* True */; if (relation === assignableRelation) { @@ -18378,6 +18879,36 @@ var ts; if (source === numberType && target.flags & 128 /* Enum */) return -1 /* True */; } + if (source.flags & 8 /* Boolean */ && target.flags & 8 /* Boolean */) { + if (source.flags & 134217728 /* PredicateType */ && target.flags & 134217728 /* PredicateType */) { + var sourcePredicate = source; + var targetPredicate = target; + if (sourcePredicate.predicate.kind !== targetPredicate.predicate.kind) { + if (reportErrors) { + reportError(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + if (sourcePredicate.predicate.kind === 1 /* Identifier */) { + var sourceIdentifierPredicate = sourcePredicate.predicate; + var targetIdentifierPredicate = targetPredicate.predicate; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + } + var related = isRelatedTo(sourcePredicate.predicate.type, targetPredicate.predicate.type, reportErrors, headMessage); + if (related === 0 /* False */ && reportErrors) { + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return related; + } + return -1 /* True */; + } if (source.flags & 1048576 /* FreshObjectLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -18471,9 +19002,6 @@ var ts; } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } - if (source.flags & 512 /* TypeParameter */ && target.flags & 512 /* TypeParameter */) { - return typeParameterIdenticalTo(source, target); - } if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target)) { @@ -18529,7 +19057,7 @@ var ts; var sourceTypes = source.types; for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { var sourceType = sourceTypes_1[_i]; - var related = typeRelatedToSomeType(sourceType, target, false); + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); if (!related) { return 0 /* False */; } @@ -18589,8 +19117,9 @@ var ts; if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } + var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1 /* True */; - for (var i = 0; i < targets.length; i++) { + for (var i = 0; i < length; i++) { var related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return 0 /* False */; @@ -18599,31 +19128,24 @@ var ts; } return result; } - function typeParameterIdenticalTo(source, target) { - // covers case when both type parameters does not have constraint (both equal to noConstraintType) - if (source.constraint === target.constraint) { - return -1 /* True */; - } - if (source.constraint === noConstraintType || target.constraint === noConstraintType) { - return 0 /* False */; - } - return isIdenticalTo(source.constraint, target.constraint); - } // Determine if two object types are related by structure. First, check if the result is already available in the global cache. // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function objectTypeRelatedTo(apparentSource, originalSource, target, reportErrors) { + function objectTypeRelatedTo(source, originalSource, target, reportErrors) { if (overflow) { return 0 /* False */; } - var id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { - // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate - // errors, we can use the cached value. Otherwise, recompute the relation - if (!elaborateErrors || (related === 3 /* FailedAndReported */)) { + if (elaborateErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported + // failure and continue computing the relation such that errors get reported. + relation[id] = 3 /* FailedAndReported */; + } + else { return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; } } @@ -18645,13 +19167,13 @@ var ts; maybeStack = []; expandingFlags = 0; } - sourceStack[depth] = apparentSource; + sourceStack[depth] = source; targetStack[depth] = target; maybeStack[depth] = {}; maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; @@ -18660,15 +19182,15 @@ var ts; result = 1 /* Maybe */; } else { - result = propertiesRelatedTo(apparentSource, target, reportErrors); + result = propertiesRelatedTo(source, target, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 0 /* Call */, reportErrors); + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 1 /* Construct */, reportErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportErrors); if (result) { - result &= stringIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= stringIndexTypesRelatedTo(source, originalSource, target, reportErrors); if (result) { - result &= numberIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= numberIndexTypesRelatedTo(source, originalSource, target, reportErrors); } } } @@ -18800,75 +19322,51 @@ var ts; } var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length && + isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignablity + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } var result = -1 /* True */; var saveErrorInfo = errorInfo; - if (kind === 1 /* Construct */) { - // Only want to compare the construct signatures for abstractness guarantees. - // Because the "abstractness" of a class is the same across all construct signatures - // (internally we are checking the corresponding declaration), it is enough to perform - // the check and report an error once over all pairs of source and target construct signatures. - // - // sourceSig and targetSig are (possibly) undefined. - // - // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. - var sourceSig = sourceSignatures[0]; - var targetSig = targetSignatures[0]; - result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); - if (result !== -1 /* True */) { - return result; - } - } outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; if (!t.hasStringLiterals || target.flags & 262144 /* FromSignature */) { - var localErrors = reportErrors; - var checkedAbstractAssignability = false; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { var s = sourceSignatures_1[_a]; if (!s.hasStringLiterals || source.flags & 262144 /* FromSignature */) { - var related = signatureRelatedTo(s, t, localErrors); + var related = signatureRelatedTo(s, t, shouldElaborateErrors); if (related) { result &= related; errorInfo = saveErrorInfo; continue outer; } - // Only report errors from the first failure - localErrors = false; + shouldElaborateErrors = false; } } + // don't elaborate the primitive apparent types (like Number) + // because the actual primitives will have already been reported. + if (shouldElaborateErrors && !isPrimitiveApparentType(source)) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } return 0 /* False */; } } return result; - function abstractSignatureRelatedTo(source, sourceSig, target, targetSig) { - if (sourceSig && targetSig) { - var sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); - var targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); - if (!sourceDecl) { - // If the source object isn't itself a class declaration, it can be freely assigned, regardless - // of whether the constructed object is abstract or not. - return -1 /* True */; - } - var sourceErasedSignature = getErasedSignature(sourceSig); - var targetErasedSignature = getErasedSignature(targetSig); - var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); - var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); - var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); - var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128 /* Abstract */; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128 /* Abstract */; - if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { - // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0 /* False */; - } - } - return -1 /* True */; - } } + /** + * See signatureAssignableTo, signatureAssignableTo + */ function signatureRelatedTo(source, target, reportErrors) { + // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; } @@ -18905,7 +19403,7 @@ var ts; var saveErrorInfo = errorInfo; var related = isRelatedTo(s, t, reportErrors); if (!related) { - related = isRelatedTo(t, s, false); + related = isRelatedTo(t, s, /*reportErrors*/ false); if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); @@ -18916,37 +19414,20 @@ var ts; } result &= related; } - if (source.typePredicate && target.typePredicate) { - var hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; - var hasDifferentTypes; - if (hasDifferentParameterIndex || - (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + if (targetReturnType.flags & 134217728 /* PredicateType */ && targetReturnType.predicate.kind === 1 /* Identifier */) { + if (!(sourceReturnType.flags & 134217728 /* PredicateType */)) { if (reportErrors) { - var sourceParamText = source.typePredicate.parameterName; - var targetParamText = target.typePredicate.parameterName; - var sourceTypeText = typeToString(source.typePredicate.type); - var targetTypeText = typeToString(target.typePredicate.type); - if (hasDifferentParameterIndex) { - reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceParamText, targetParamText); - } - else if (hasDifferentTypes) { - reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceTypeText, targetTypeText); - } - reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, sourceParamText + " is " + sourceTypeText, targetParamText + " is " + targetTypeText); + reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); } return 0 /* False */; } } - else if (!source.typePredicate && target.typePredicate) { - if (reportErrors) { - reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); - } - return 0 /* False */; - } - var targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) - return result; - var sourceReturnType = getReturnTypeOfSignature(source); return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); } function signaturesIdenticalTo(source, target, kind) { @@ -18956,8 +19437,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var i = 0, len = sourceSignatures.length; i < len; ++i) { - var related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + for (var i = 0, len = sourceSignatures.length; i < len; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); if (!related) { return 0 /* False */; } @@ -19016,7 +19497,7 @@ var ts; var related; if (sourceStringType && sourceNumberType) { // If we know for sure we're testing both string and numeric index types then only report errors from the second one - related = isRelatedTo(sourceStringType, targetType, false) || isRelatedTo(sourceNumberType, targetType, reportErrors); + related = isRelatedTo(sourceStringType, targetType, /*reportErrors*/ false) || isRelatedTo(sourceNumberType, targetType, reportErrors); } else { related = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors); @@ -19042,6 +19523,38 @@ var ts; } return 0 /* False */; } + function enumRelatedTo(source, target) { + 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 */)) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + return 0 /* False */; + } + } + } + return -1 /* True */; + } + } + // Return true if the given type is the constructor type for an abstract class + function isAbstractConstructorType(type) { + if (type.flags & 65536 /* Anonymous */) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && declaration.flags & 128 /* Abstract */) { + return true; + } + } + } + return false; } // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case // when structural type comparisons have been started for 10 or more instantiations of the same generic type. It is possible, @@ -19065,7 +19578,7 @@ var ts; return false; } function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypes) !== 0 /* False */; + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; } function compareProperties(sourceProp, targetProp, compareTypes) { // Two members are considered identical when @@ -19108,33 +19621,30 @@ var ts; } return false; } - function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; } if (!(isMatchingSignature(source, target, partialMatch))) { return 0 /* False */; } - var result = -1 /* True */; - if (source.typeParameters && target.typeParameters) { - if (source.typeParameters.length !== target.typeParameters.length) { - return 0 /* False */; - } - for (var i = 0, len = source.typeParameters.length; i < len; ++i) { - var related = compareTypes(source.typeParameters[i], target.typeParameters[i]); - if (!related) { - return 0 /* False */; - } - result &= related; - } - } - else if (source.typeParameters || target.typeParameters) { + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) { return 0 /* False */; } // Spec 1.0 Section 3.8.3 & 3.8.4: // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N source = getErasedSignature(source); target = getErasedSignature(target); + var result = -1 /* True */; var targetLen = target.parameters.length; for (var i = 0; i < targetLen; i++) { var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); @@ -19262,10 +19772,13 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); } function getWidenedType(type) { - if (type.flags & 6291456 /* RequiresWidening */) { + if (type.flags & 140509184 /* RequiresWidening */) { if (type.flags & (32 /* Undefined */ | 64 /* Null */)) { return anyType; } + if (type.flags & 134217728 /* PredicateType */) { + return booleanType; + } if (type.flags & 524288 /* ObjectLiteral */) { return getWidenedTypeOfObjectLiteral(type); } @@ -19340,13 +19853,13 @@ var ts; ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -19393,13 +19906,7 @@ var ts; } } function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var unused = typeParameters_1[_i]; - inferences.push({ - primary: undefined, secondary: undefined, isFixed: false - }); - } + var inferences = ts.map(typeParameters, createTypeInferencesObject); return { typeParameters: typeParameters, inferUnionTypes: inferUnionTypes, @@ -19407,6 +19914,13 @@ var ts; inferredTypes: new Array(typeParameters.length) }; } + function createTypeInferencesObject() { + return { + primary: undefined, + secondary: undefined, + isFixed: false + }; + } function inferTypes(context, source, target) { var sourceStack; var targetStack; @@ -19422,6 +19936,29 @@ var ts; return false; } function inferFromTypes(source, target) { + if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || + source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { + // Source and target are both unions or both intersections. First, find each + // target constituent type that has an identically matching source constituent + // type, and for each such target constituent type infer from the type to itself. + // When inferring from a type to itself we effectively find all type parameter + // occurrences within that type and infer themselves as their type arguments. + var matchingTypes; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (typeIdenticalToSomeType(t, source.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } if (target.flags & 512 /* 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). @@ -19463,6 +20000,11 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } + else if (source.flags & 134217728 /* PredicateType */ && target.flags & 134217728 /* PredicateType */) { + if (source.predicate.kind === target.predicate.kind) { + inferFromTypes(source.predicate.type, target.predicate.type); + } + } 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; @@ -19476,8 +20018,8 @@ var ts; var typeParameterCount = 0; var typeParameter; // First infer to each type in union or intersection that isn't a type parameter - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var t = targetTypes_2[_i]; + 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)) { typeParameter = t; typeParameterCount++; @@ -19499,16 +20041,18 @@ var ts; else if (source.flags & 49152 /* UnionOrIntersection */) { // Source is a union or intersection type, infer from each consituent type var sourceTypes = source.types; - for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { - var sourceType = sourceTypes_3[_a]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 /* ObjectType */ && (target.flags & (4096 /* Reference */ | 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, a tuple type, the type of a method, or a type literal, infer from members + 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 (isInProcess(source, target)) { return; } @@ -19554,17 +20098,7 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - if (source.typePredicate && target.typePredicate) { - if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { - // Return types from type predicates are treated as booleans. In order to infer types - // from type predicates we would need to infer using the type within the type predicate - // (i.e. 'Foo' from 'x is Foo'). - inferFromTypes(source.typePredicate.type, target.typePredicate.type); - } - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } function inferFromIndexTypes(source, target, sourceKind, targetKind) { var targetIndexType = getIndexTypeOfType(target, targetKind); @@ -19576,6 +20110,29 @@ var ts; } } } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 16384 /* Union */ ? getUnionType(reducedTypes, /*noSubtypeReduction*/ true) : getIntersectionType(reducedTypes); + } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; @@ -19599,10 +20156,16 @@ var ts; inferredType = emptyObjectType; inferenceSucceeded = true; } + context.inferredTypes[index] = inferredType; // Only do the constraint check if inference succeeded (to prevent cascading errors) if (inferenceSucceeded) { var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); - inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + context.inferredTypes[index] = inferredType = instantiatedConstraint; + } + } } else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { // If inference failed, it is necessary to record the index of the failed type parameter (the one we are on). @@ -19610,7 +20173,6 @@ var ts; // So if this failure is on preceding type parameter, this type parameter is the new failure index. context.failedTypeParameterIndex = index; } - context.inferredTypes[index] = inferredType; } return inferredType; } @@ -19620,9 +20182,6 @@ var ts; } return context.inferredTypes; } - function hasAncestor(node, kind) { - return ts.getAncestor(node, kind) !== undefined; - } // EXPRESSION TYPE CHECKING function getResolvedSymbol(node) { var links = getNodeLinks(node); @@ -19649,26 +20208,6 @@ var ts; } ts.Debug.fail("should not get here"); } - // For a union type, remove all constituent types that are of the given type kind (when isOfTypeKind is true) - // or not of the given type kind (when isOfTypeKind is false) - function removeTypesFromUnionType(type, typeKind, isOfTypeKind, allowEmptyUnionResult) { - if (type.flags & 16384 /* Union */) { - var types = type.types; - if (ts.forEach(types, function (t) { return !!(t.flags & typeKind) === isOfTypeKind; })) { - // Above we checked if we have anything to remove, now use the opposite test to do the removal - var narrowedType = getUnionType(ts.filter(types, function (t) { return !(t.flags & typeKind) === isOfTypeKind; })); - if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { - return narrowedType; - } - } - } - else if (allowEmptyUnionResult && !!(type.flags & typeKind) === isOfTypeKind) { - // Use getUnionType(emptyArray) instead of emptyObjectType in case the way empty union types - // are represented ever changes. - return getUnionType(emptyArray); - } - return type; - } function hasInitializer(node) { return !!(node.initializer || ts.isBindingPattern(node.parent) && hasInitializer(node.parent.parent)); } @@ -19687,10 +20226,7 @@ var ts; return links.assignmentChecks[symbol.id] = isAssignedIn(node); function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 56 /* FirstAssignment */ && node.operatorToken.kind <= 68 /* LastAssignment */) { - var n = node.left; - while (n.kind === 172 /* ParenthesizedExpression */) { - n = n.expression; - } + var n = skipParenthesizedNodes(node.left); if (n.kind === 69 /* Identifier */ && getResolvedSymbol(n) === symbol) { return true; } @@ -19705,55 +20241,55 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return isAssignedInBinaryExpression(node); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: return isAssignedInVariableDeclaration(node); - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: - case 172 /* ParenthesizedExpression */: - case 179 /* PrefixUnaryExpression */: - case 175 /* DeleteExpression */: - case 178 /* AwaitExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 180 /* PostfixUnaryExpression */: - case 184 /* YieldExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 192 /* Block */: - case 193 /* VariableStatement */: - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 204 /* ReturnStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - case 235 /* JsxOpeningElement */: - case 240 /* JsxExpression */: + case 163 /* ObjectBindingPattern */: + case 164 /* ArrayBindingPattern */: + case 166 /* ArrayLiteralExpression */: + case 167 /* ObjectLiteralExpression */: + case 168 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: + case 173 /* TypeAssertionExpression */: + case 191 /* AsExpression */: + case 174 /* ParenthesizedExpression */: + case 181 /* PrefixUnaryExpression */: + case 177 /* DeleteExpression */: + case 180 /* AwaitExpression */: + case 178 /* TypeOfExpression */: + case 179 /* VoidExpression */: + case 182 /* PostfixUnaryExpression */: + case 186 /* YieldExpression */: + case 184 /* ConditionalExpression */: + case 187 /* SpreadElementExpression */: + case 194 /* Block */: + case 195 /* VariableStatement */: + case 197 /* ExpressionStatement */: + case 198 /* IfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 206 /* ReturnStatement */: + case 207 /* WithStatement */: + case 208 /* SwitchStatement */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: + case 209 /* LabeledStatement */: + case 210 /* ThrowStatement */: + case 211 /* TryStatement */: + case 246 /* CatchClause */: + case 235 /* JsxElement */: + case 236 /* JsxSelfClosingElement */: + case 240 /* JsxAttribute */: + case 241 /* JsxSpreadAttribute */: + case 237 /* JsxOpeningElement */: + case 242 /* JsxExpression */: return ts.forEachChild(node, isAssignedIn); } return false; @@ -19765,59 +20301,73 @@ var ts; // Only narrow when symbol is variable of type any or an object, union, or type parameter type if (node && symbol.flags & 3 /* Variable */) { if (isTypeAny(type) || type.flags & (80896 /* ObjectType */ | 16384 /* Union */ | 512 /* TypeParameter */)) { + var declaration = ts.getDeclarationOfKind(symbol, 213 /* VariableDeclaration */); + var top_1 = declaration && getDeclarationContainer(declaration); + var originalType = type; + var nodeStack = []; loop: while (node.parent) { var child = node; node = node.parent; - var narrowedType = type; switch (node.kind) { - case 196 /* IfStatement */: - // In a branch of an if statement, narrow based on controlling expression - if (child !== node.expression) { - narrowedType = narrowType(type, node.expression, /*assumeTrue*/ child === node.thenStatement); - } + case 198 /* IfStatement */: + case 184 /* ConditionalExpression */: + case 183 /* BinaryExpression */: + nodeStack.push({ node: node, child: child }); break; - case 182 /* ConditionalExpression */: - // In a branch of a conditional expression, narrow based on controlling condition - if (child !== node.condition) { - narrowedType = narrowType(type, node.condition, /*assumeTrue*/ child === node.whenTrue); - } - break; - case 181 /* BinaryExpression */: - // In the right operand of an && or ||, narrow based on left operand - if (child === node.right) { - if (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { - narrowedType = narrowType(type, node.left, /*assumeTrue*/ true); - } - else if (node.operatorToken.kind === 52 /* BarBarToken */) { - narrowedType = narrowType(type, node.left, /*assumeTrue*/ false); - } - } - break; - case 248 /* SourceFile */: - case 218 /* ModuleDeclaration */: - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 144 /* Constructor */: - // Stop at the first containing function or module declaration + case 250 /* SourceFile */: + case 220 /* ModuleDeclaration */: + // Stop at the first containing file or module declaration break loop; } - // Use narrowed type if construct contains no assignments to variable - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; - } - type = narrowedType; + if (node === top_1) { + break; } } + var nodes; + while (nodes = nodeStack.pop()) { + var node_1 = nodes.node, child = nodes.child; + switch (node_1.kind) { + case 198 /* IfStatement */: + // In a branch of an if statement, narrow based on controlling expression + if (child !== node_1.expression) { + type = narrowType(type, node_1.expression, /*assumeTrue*/ child === node_1.thenStatement); + } + break; + case 184 /* ConditionalExpression */: + // In a branch of a conditional expression, narrow based on controlling condition + if (child !== node_1.condition) { + type = narrowType(type, node_1.condition, /*assumeTrue*/ child === node_1.whenTrue); + } + break; + case 183 /* BinaryExpression */: + // In the right operand of an && or ||, narrow based on left operand + if (child === node_1.right) { + if (node_1.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + type = narrowType(type, node_1.left, /*assumeTrue*/ true); + } + else if (node_1.operatorToken.kind === 52 /* BarBarToken */) { + type = narrowType(type, node_1.left, /*assumeTrue*/ false); + } + } + break; + default: + ts.Debug.fail("Unreachable!"); + } + // Use original type if construct contains assignments to variable + if (type !== originalType && isVariableAssignedWithin(symbol, node_1)) { + type = originalType; + } + } + // Preserve old top-level behavior - if the branch is really an empty set, revert to prior type + if (type === emptyUnionType) { + type = originalType; + } } } return type; function narrowTypeByEquality(type, expr, assumeTrue) { // Check that we have 'typeof ' on the left and string literal on the right - if (expr.left.kind !== 176 /* TypeOfExpression */ || expr.right.kind !== 9 /* StringLiteral */) { + if (expr.left.kind !== 178 /* TypeOfExpression */ || expr.right.kind !== 9 /* StringLiteral */) { return type; } var left = expr.left; @@ -19825,31 +20375,34 @@ var ts; if (left.expression.kind !== 69 /* Identifier */ || getResolvedSymbol(left.expression) !== symbol) { return type; } - var typeInfo = primitiveTypeInfo[right.text]; if (expr.operatorToken.kind === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue) { - // Assumed result is true. If check was not for a primitive type, remove all primitive types - if (!typeInfo) { - return removeTypesFromUnionType(type, /*typeKind*/ 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */ | 16777216 /* ESSymbol */, - /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); - } - // Check was for a primitive type, return that primitive type if it is a subtype - if (isTypeSubtypeOf(typeInfo.type, type)) { - return typeInfo.type; - } - // Otherwise, remove all types that aren't of the primitive type kind. This can happen when the type is - // union of enum types and other types. - return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ false, /*allowEmptyUnionResult*/ false); + var typeInfo = primitiveTypeInfo[right.text]; + // Don't narrow `undefined` + if (typeInfo && typeInfo.type === undefinedType) { + return type; + } + // If the type to be narrowed is any and we're checking a primitive with assumeTrue=true, return the primitive + if (!!(type.flags & 1 /* Any */) && typeInfo && assumeTrue) { + return typeInfo.type; + } + var flags; + if (typeInfo) { + flags = typeInfo.flags; } else { - // Assumed result is false. If check was for a primitive type, remove that primitive type - if (typeInfo) { - return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); - } - // Otherwise we don't have enough information to do anything. - return type; + assumeTrue = !assumeTrue; + flags = 132 /* NumberLike */ | 258 /* StringLike */ | 16777216 /* ESSymbol */ | 8 /* Boolean */; + } + // At this point we can bail if it's not a union + if (!(type.flags & 16384 /* Union */)) { + // If the active non-union type would be removed from a union by this type guard, return an empty union + return filterUnion(type) ? type : emptyUnionType; + } + return getUnionType(ts.filter(type.types, filterUnion), /*noSubtypeReduction*/ true); + function filterUnion(type) { + return assumeTrue === !!(type.flags & flags); } } function narrowTypeByAnd(type, expr, assumeTrue) { @@ -19862,7 +20415,7 @@ var ts; // and the second operand was false. We narrow with those assumptions and union the two resulting types. return getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ false), - narrowType(narrowType(type, expr.left, /*assumeTrue*/ true), expr.right, /*assumeTrue*/ false) + narrowType(type, expr.right, /*assumeTrue*/ false) ]); } } @@ -19872,7 +20425,7 @@ var ts; // and the second operand was true. We narrow with those assumptions and union the two resulting types. return getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ true), - narrowType(narrowType(type, expr.left, /*assumeTrue*/ false), expr.right, /*assumeTrue*/ true) + narrowType(type, expr.right, /*assumeTrue*/ true) ]); } else { @@ -19913,17 +20466,17 @@ var ts; } } if (targetType) { - if (!assumeTrue) { - if (type.flags & 16384 /* Union */) { - return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, targetType); })); - } - return type; - } - return getNarrowedType(type, targetType); + return getNarrowedType(type, targetType, assumeTrue); } return type; } - function getNarrowedType(originalType, narrowedTypeCandidate) { + function getNarrowedType(originalType, narrowedTypeCandidate, assumeTrue) { + if (!assumeTrue) { + if (originalType.flags & 16384 /* Union */) { + return getUnionType(ts.filter(originalType.types, function (t) { return !isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } // If the current type is a union type, remove all constituents that aren't assignable to target. If that produces // 0 candidates, fall back to the assignability check if (originalType.flags & 16384 /* Union */) { @@ -19943,28 +20496,62 @@ var ts; return type; } var signature = getResolvedSignature(expr); - if (signature.typePredicate && - expr.arguments[signature.typePredicate.parameterIndex] && - getSymbolAtLocation(expr.arguments[signature.typePredicate.parameterIndex]) === symbol) { - if (!assumeTrue) { - if (type.flags & 16384 /* Union */) { - return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, signature.typePredicate.type); })); - } - return type; + var predicateType = getReturnTypeOfSignature(signature); + if (!predicateType || !(predicateType.flags & 134217728 /* PredicateType */)) { + return type; + } + var predicate = predicateType.predicate; + if (ts.isIdentifierTypePredicate(predicate)) { + var callExpression = expr; + if (callExpression.arguments[predicate.parameterIndex] && + getSymbolAtTypePredicatePosition(callExpression.arguments[predicate.parameterIndex]) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); } - return getNarrowedType(type, signature.typePredicate.type); + } + else { + var expression = skipParenthesizedNodes(expr.expression); + return narrowTypeByThisTypePredicate(type, predicate, expression, assumeTrue); } return type; } + function narrowTypeByTypePredicateMember(type, expr, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + var memberType = getTypeOfExpression(expr); + if (!(memberType.flags & 134217728 /* PredicateType */)) { + return type; + } + return narrowTypeByThisTypePredicate(type, memberType.predicate, expr, assumeTrue); + } + function narrowTypeByThisTypePredicate(type, predicate, expression, assumeTrue) { + if (expression.kind === 169 /* ElementAccessExpression */ || expression.kind === 168 /* PropertyAccessExpression */) { + var accessExpression = expression; + var possibleIdentifier = skipParenthesizedNodes(accessExpression.expression); + if (possibleIdentifier.kind === 69 /* Identifier */ && getSymbolAtTypePredicatePosition(possibleIdentifier) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); + } + } + return type; + } + function getSymbolAtTypePredicatePosition(expr) { + expr = skipParenthesizedNodes(expr); + switch (expr.kind) { + case 69 /* Identifier */: + case 168 /* PropertyAccessExpression */: + case 135 /* QualifiedName */: + return getSymbolOfEntityNameOrPropertyAccessExpression(expr); + } + } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 168 /* CallExpression */: + case 170 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: var operator = expr.operatorToken.kind; if (operator === 32 /* EqualsEqualsEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -19979,15 +20566,24 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: if (expr.operator === 49 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } break; + case 169 /* ElementAccessExpression */: + case 168 /* PropertyAccessExpression */: + return narrowTypeByTypePredicateMember(type, expr, assumeTrue); } return type; } } + function skipParenthesizedNodes(expression) { + while (expression.kind === 174 /* ParenthesizedExpression */) { + expression = expression.expression; + } + return expression; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. @@ -19998,7 +20594,7 @@ var ts; // can explicitly bound arguments objects if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 174 /* ArrowFunction */) { + if (container.kind === 176 /* ArrowFunction */) { if (languageVersion < 2 /* ES6 */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } @@ -20029,7 +20625,7 @@ var ts; function checkBlockScopedBindingCapturedInLoop(node, symbol) { if (languageVersion >= 2 /* ES6 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 244 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 246 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -20045,12 +20641,12 @@ var ts; // nesting structure: // (variable declaration or binding element) -> variable declaration list -> container container = symbol.valueDeclaration; - while (container.kind !== 212 /* VariableDeclarationList */) { + while (container.kind !== 214 /* VariableDeclarationList */) { container = container.parent; } // get the parent of variable declaration list container = container.parent; - if (container.kind === 193 /* VariableStatement */) { + if (container.kind === 195 /* VariableStatement */) { // if parent is variable statement - get its parent container = container.parent; } @@ -20085,17 +20681,17 @@ var ts; var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 174 /* ArrowFunction */) { + if (container.kind === 176 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code needToCaptureLexicalThis = (languageVersion < 2 /* ES6 */); } switch (container.kind) { - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; @@ -20121,6 +20717,21 @@ var ts; var symbol = getSymbolOfNode(container.parent); return container.flags & 64 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; } + // If this is a function in a JS file, it might be a class method. Check if it's the RHS + // of a x.prototype.y = function [name]() { .... } + if (ts.isInJavaScriptFile(node) && container.kind === 175 /* FunctionExpression */) { + if (ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') + var className = container.parent // x.protoype.y = f + .left // x.prototype.y + .expression // x.prototype + .expression; // x + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + return getInferredClassType(classSymbol); + } + } + } return anyType; } function isInConstructorArgumentInitializer(node, constructorDecl) { @@ -20132,55 +20743,75 @@ var ts; return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 168 /* CallExpression */ && node.parent.expression === node; - var classDeclaration = ts.getContainingClass(node); - var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - var container = ts.getSuperContainer(node, /*includeFunctions*/ true); + var isCallExpression = node.parent.kind === 170 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; if (!isCallExpression) { // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting - while (container && container.kind === 174 /* ArrowFunction */) { - container = ts.getSuperContainer(container, /*includeFunctions*/ true); + while (container && container.kind === 176 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; } } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; - // always set NodeCheckFlags for 'super' expression node - if (canUseSuperExpression) { - if ((container.flags & 64 /* Static */) || isCallExpression) { - nodeCheckFlag = 512 /* SuperStatic */; - } - else { - nodeCheckFlag = 256 /* SuperInstance */; - } - getNodeLinks(node).flags |= nodeCheckFlag; - if (needToCaptureLexicalThis) { - // call expressions are allowed only in constructors so they should always capture correct 'this' - // super property access expressions can also appear in arrow functions - - // in this case they should also use correct lexical this - captureLexicalThis(node.parent, container); - } - } - if (!baseClassType) { - if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } if (!canUseSuperExpression) { - if (container && container.kind === 136 /* ComputedPropertyName */) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = node; + while (current && current !== container && current.kind !== 136 /* ComputedPropertyName */) { + current = current.parent; + } + if (current && current.kind === 136 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 167 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } else { error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); } return unknownType; } + if ((container.flags & 64 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 167 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES6 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } if (container.kind === 144 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); @@ -20203,8 +20834,8 @@ var ts; // 'super' property access is allowed // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor - // topmost container must be something that is directly nested in the class declaration - if (container && ts.isClassLike(container.parent)) { + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 167 /* ObjectLiteralExpression */) { if (container.flags & 64 /* Static */) { return container.kind === 143 /* MethodDeclaration */ || container.kind === 142 /* MethodSignature */ || @@ -20327,7 +20958,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 170 /* TaggedTemplateExpression */) { + if (template.parent.kind === 172 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -20350,6 +20981,11 @@ var ts; } return type; } + else if (operator === 51 /* AmpersandAmpersandToken */ || operator === 24 /* CommaToken */) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } return undefined; } // Apply a mapping function to a contextual type and return the resulting type. If the contextual type @@ -20362,8 +20998,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var current = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -20449,22 +21085,20 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForJsxExpression(expr) { - // Contextual type only applies to JSX expressions that are in attribute assignments (not in 'Children' positions) - if (expr.parent.kind === 238 /* JsxAttribute */) { - var attrib = expr.parent; - var attrsType = getJsxElementAttributesType(attrib.parent); + function getContextualTypeForJsxAttribute(attribute) { + var kind = attribute.kind; + var jsxElement = attribute.parent; + var attrsType = getJsxElementAttributesType(jsxElement); + if (attribute.kind === 240 /* JsxAttribute */) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } - else { - return getTypeOfPropertyOfType(attrsType, attrib.name.text); - } + return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - if (expr.kind === 239 /* JsxSpreadAttribute */) { - return getJsxElementAttributesType(expr.parent); + else if (attribute.kind === 241 /* JsxSpreadAttribute */) { + return attrsType; } - return undefined; + ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -20499,39 +21133,41 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: case 138 /* Parameter */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 163 /* BindingElement */: + case 165 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 174 /* ArrowFunction */: - case 204 /* ReturnStatement */: + case 176 /* ArrowFunction */: + case 206 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 184 /* YieldExpression */: + case 186 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 173 /* TypeAssertionExpression */: + case 191 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 190 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 183 /* TemplateExpression */); + case 192 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 185 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return getContextualType(parent); - case 240 /* JsxExpression */: - case 239 /* JsxSpreadAttribute */: - return getContextualTypeForJsxExpression(parent); + case 242 /* JsxExpression */: + return getContextualType(parent); + case 240 /* JsxAttribute */: + case 241 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); } return undefined; } @@ -20547,7 +21183,7 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 173 /* FunctionExpression */ || node.kind === 174 /* ArrowFunction */; + return node.kind === 175 /* FunctionExpression */ || node.kind === 176 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -20573,15 +21209,15 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { // This signature will contribute to contextual union signature signatureList = [signature]; } - else if (!compareSignatures(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypes)) { + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { // Signatures aren't identical, do not use return undefined; } @@ -20624,13 +21260,13 @@ var ts; // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. function isAssignmentTarget(node) { var parent = node.parent; - if (parent.kind === 181 /* BinaryExpression */ && parent.operatorToken.kind === 56 /* EqualsToken */ && parent.left === node) { + if (parent.kind === 183 /* BinaryExpression */ && parent.operatorToken.kind === 56 /* EqualsToken */ && parent.left === node) { return true; } - if (parent.kind === 245 /* PropertyAssignment */) { + if (parent.kind === 247 /* PropertyAssignment */) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 164 /* ArrayLiteralExpression */) { + if (parent.kind === 166 /* ArrayLiteralExpression */) { return isAssignmentTarget(parent); } return false; @@ -20646,8 +21282,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); } function hasDefaultValue(node) { - return (node.kind === 163 /* BindingElement */ && !!node.initializer) || - (node.kind === 181 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */); + return (node.kind === 165 /* BindingElement */ && !!node.initializer) || + (node.kind === 183 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -20656,7 +21292,7 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 185 /* SpreadElementExpression */) { + if (inDestructuringPattern && e.kind === 187 /* SpreadElementExpression */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -20680,7 +21316,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 185 /* SpreadElementExpression */; + hasSpreadElement = hasSpreadElement || e.kind === 187 /* SpreadElementExpression */; } if (!hasSpreadElement) { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such @@ -20695,7 +21331,7 @@ var ts; var pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 162 /* ArrayBindingPattern */ || pattern.kind === 164 /* ArrayLiteralExpression */)) { + if (pattern && (pattern.kind === 164 /* ArrayBindingPattern */ || pattern.kind === 166 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -20703,7 +21339,7 @@ var ts; elementTypes.push(contextualType.elementTypes[i]); } else { - if (patternElement.kind !== 187 /* OmittedExpression */) { + if (patternElement.kind !== 189 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -20775,24 +21411,24 @@ var ts; var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 161 /* ObjectBindingPattern */ || contextualType.pattern.kind === 165 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 163 /* ObjectBindingPattern */ || contextualType.pattern.kind === 167 /* ObjectLiteralExpression */); var typeFlags = 0; var patternWithComputedProperties = false; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 245 /* PropertyAssignment */ || - memberDecl.kind === 246 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 247 /* PropertyAssignment */ || + memberDecl.kind === 248 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 245 /* PropertyAssignment */) { + if (memberDecl.kind === 247 /* PropertyAssignment */) { type = checkPropertyAssignment(memberDecl, contextualMapper); } else if (memberDecl.kind === 143 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 246 /* ShorthandPropertyAssignment */); + ts.Debug.assert(memberDecl.kind === 248 /* ShorthandPropertyAssignment */); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; @@ -20800,8 +21436,8 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 245 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 246 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 247 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 248 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912 /* Optional */; } @@ -20893,38 +21529,22 @@ var ts; checkJsxOpeningLikeElement(node); return jsxElementType || anyType; } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 69 /* Identifier */) { - return lhs.text === rhs.text; - } - return lhs.right.text === rhs.right.text && - tagNamesAreEquivalent(lhs.left, rhs.left); - } function checkJsxElement(node) { // Check attributes checkJsxOpeningLikeElement(node.openingElement); - // Check that the closing tag matches - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - error(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNode(node.openingElement.tagName)); - } - else { - // Perform resolution on the closing tag so that rename/go to definition/etc work - getJsxElementTagSymbol(node.closingElement); - } + // Perform resolution on the closing tag so that rename/go to definition/etc work + getJsxElementTagSymbol(node.closingElement); // Check children for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 240 /* JsxExpression */: + case 242 /* JsxExpression */: checkJsxExpression(child); break; - case 233 /* JsxElement */: + case 235 /* JsxElement */: checkJsxElement(child); break; - case 234 /* JsxSelfClosingElement */: + case 236 /* JsxSelfClosingElement */: checkJsxSelfClosingElement(child); break; } @@ -21006,12 +21626,11 @@ var ts; } return type; } - /// Returns the type JSX.IntrinsicElements. May return `unknownType` if that type is not present. - function getJsxIntrinsicElementsType() { - if (!jsxIntrinsicElementsType) { - jsxIntrinsicElementsType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.IntrinsicElements) || unknownType; + function getJsxType(name) { + if (jsxTypes[name] === undefined) { + return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType; } - return jsxIntrinsicElementsType; + return jsxTypes[name]; } /// Given a JSX opening element or self-closing element, return the symbol of the property that the tag name points to if /// this is an intrinsic tag. This might be a named @@ -21020,7 +21639,6 @@ var ts; /// type or factory function. /// Otherwise, returns unknownSymbol. function getJsxElementTagSymbol(node) { - var flags = 8 /* UnknownElement */; var links = getNodeLinks(node); if (!links.resolvedSymbol) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -21032,7 +21650,7 @@ var ts; } return links.resolvedSymbol; function lookupIntrinsicTag(node) { - var intrinsicElementsType = getJsxIntrinsicElementsType(); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { // Property case var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); @@ -21060,7 +21678,7 @@ var ts; var valueSymbol = resolveJsxTagName(node); // Look up the value in the current scope if (valueSymbol && valueSymbol !== unknownSymbol) { - links.jsxFlags |= 4 /* ClassElement */; + links.jsxFlags |= 4 /* ValueElement */; if (valueSymbol.flags & 8388608 /* Alias */) { markAliasSymbolAsReferenced(valueSymbol); } @@ -21086,7 +21704,7 @@ var ts; function getJsxElementInstanceType(node) { // There is no such thing as an instance type for a non-class element. This // line shouldn't be hit. - ts.Debug.assert(!!(getNodeLinks(node).jsxFlags & 4 /* ClassElement */), "Should not call getJsxElementInstanceType on non-class Element"); + ts.Debug.assert(!!(getNodeLinks(node).jsxFlags & 4 /* ValueElement */), "Should not call getJsxElementInstanceType on non-class Element"); var classSymbol = getJsxElementTagSymbol(node); if (classSymbol === unknownSymbol) { // Couldn't find the class instance type. Error has already been issued @@ -21108,13 +21726,7 @@ var ts; return unknownType; } } - var returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); - // Issue an error if this return type isn't assignable to JSX.ElementClass - var elemClassType = getJsxGlobalElementClassType(); - if (elemClassType) { - checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - return returnType; + return getUnionType(signatures.map(getReturnTypeOfSignature)); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesPropery doesn't exist (which means all @@ -21156,8 +21768,27 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedJsxType) { var sym = getJsxElementTagSymbol(node); - if (links.jsxFlags & 4 /* ClassElement */) { + if (links.jsxFlags & 4 /* ValueElement */) { + // Get the element instance type (the result of newing or invoking this tag) var elemInstanceType = getJsxElementInstanceType(node); + // Is this is a stateless function component? See if its single signature is + // assignable to the JSX Element Type + var callSignature = getSingleCallSignature(getTypeOfSymbol(sym)); + var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); + var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType) && (paramType.flags & 80896 /* ObjectType */)) { + // Intersect in JSX.IntrinsicAttributes if it exists + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return paramType; + } + // Issue an error if this return type isn't assignable to JSX.ElementClass + var elemClassType = getJsxGlobalElementClassType(); + if (elemClassType) { + checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } @@ -21177,14 +21808,34 @@ var ts; return links.resolvedJsxType = emptyObjectType; } else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + // Props is of type 'any' or unknown return links.resolvedJsxType = attributesType; } - else if (!(attributesType.flags & 80896 /* ObjectType */)) { - error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_must_be_an_object_type, typeToString(attributesType)); + else if (attributesType.flags & 16384 /* 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 links.resolvedJsxType = anyType; } else { - return links.resolvedJsxType = attributesType; + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return links.resolvedJsxType = apparentAttributesType; } } } @@ -21219,7 +21870,7 @@ var ts; } /// Returns all the properties of the Jsx.IntrinsicElements interface function getJsxIntrinsicTagNames() { - var intrinsics = getJsxIntrinsicElementsType(); + var intrinsics = getJsxType(JsxNames.IntrinsicElements); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } function checkJsxPreconditions(errorNode) { @@ -21236,14 +21887,13 @@ var ts; function checkJsxOpeningLikeElement(node) { checkGrammarJsxElement(node); checkJsxPreconditions(node); - // If we're compiling under --jsx react, the symbol 'React' should - // be marked as 'used' so we don't incorrectly elide its import. And if there - // is no 'React' symbol in scope, we should issue an error. - if (compilerOptions.jsx === 2 /* React */) { - var reactSym = resolveName(node.tagName, "React", 107455 /* Value */, ts.Diagnostics.Cannot_find_name_0, "React"); - if (reactSym) { - getSymbolLinks(reactSym).referenced = true; - } + // The reactNamespace symbol should be marked as 'used' so we don't incorrectly elide its import. And if there + // is no reactNamespace symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); + if (reactSym) { + getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = {}; @@ -21252,11 +21902,11 @@ var ts; // thus should have their types ignored var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 238 /* JsxAttribute */) { + if (node.attributes[i].kind === 240 /* JsxAttribute */) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 239 /* JsxSpreadAttribute */); + ts.Debug.assert(node.attributes[i].kind === 241 /* JsxSpreadAttribute */); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -21303,7 +21953,7 @@ var ts; var flags = getDeclarationFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (left.kind === 95 /* SuperKeyword */) { - var errorNode = node.kind === 166 /* PropertyAccessExpression */ ? + var errorNode = node.kind === 168 /* PropertyAccessExpression */ ? node.name : node.right; // TS 1.0 spec (April 2014): 4.8.2 @@ -21313,7 +21963,7 @@ var ts; // - In a static member function or static member accessor // where this references the constructor function object of a derived class, // a super property access is permitted and must specify a public static member function of the base class. - if (getDeclarationKindFromSymbol(prop) !== 143 /* MethodDeclaration */) { + if (languageVersion < 2 /* ES6 */ && getDeclarationKindFromSymbol(prop) !== 143 /* MethodDeclaration */) { // `prop` refers to a *property* declared in the super class // rather than a *method*, so it does not satisfy the above criteria. error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); @@ -21400,7 +22050,7 @@ var ts; return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 166 /* PropertyAccessExpression */ + var left = node.kind === 168 /* PropertyAccessExpression */ ? node.expression : node.left; var type = checkExpression(left); @@ -21416,7 +22066,7 @@ var ts; // Grammar checking if (!node.argumentExpression) { var sourceFile = getSourceFile(node); - if (node.parent.kind === 169 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 171 /* NewExpression */ && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -21497,7 +22147,7 @@ var ts; if (indexArgumentExpression.kind === 9 /* StringLiteral */ || indexArgumentExpression.kind === 8 /* NumericLiteral */) { return indexArgumentExpression.text; } - if (indexArgumentExpression.kind === 167 /* ElementAccessExpression */ || indexArgumentExpression.kind === 166 /* PropertyAccessExpression */) { + if (indexArgumentExpression.kind === 169 /* ElementAccessExpression */ || indexArgumentExpression.kind === 168 /* PropertyAccessExpression */) { var value = getConstantValue(indexArgumentExpression); if (value !== undefined) { return value.toString(); @@ -21552,7 +22202,7 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 172 /* TaggedTemplateExpression */) { checkExpression(node.template); } else if (node.kind !== 139 /* Decorator */) { @@ -21621,7 +22271,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 185 /* SpreadElementExpression */) { + if (arg && arg.kind === 187 /* SpreadElementExpression */) { return i; } } @@ -21633,13 +22283,13 @@ var ts; var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments var isDecorator; var spreadArgIndex = -1; - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 172 /* TaggedTemplateExpression */) { var tagExpression = node; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length adjustedArgCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 183 /* TemplateExpression */) { + if (tagExpression.template.kind === 185 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var templateExpression = tagExpression.template; @@ -21665,7 +22315,7 @@ var ts; var callExpression = node; if (!callExpression.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(callExpression.kind === 169 /* NewExpression */); + ts.Debug.assert(callExpression.kind === 171 /* NewExpression */); return signature.minArgumentCount === 0; } // For IDE scenarios we may have an incomplete call, so a trailing comma is tantamount to adding another argument. @@ -21717,7 +22367,7 @@ var ts; } function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; - var inferenceMapper = createInferenceMapper(context); + var inferenceMapper = getInferenceMapper(context); // Clear out all the inference results from the last time inferTypeArguments was called on this context for (var i = 0; i < typeParameters.length; i++) { // As an optimization, we don't have to clear (and later recompute) inferred types @@ -21744,7 +22394,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 187 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 189 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); // If the effective argument type is 'undefined', there is no synthetic type @@ -21775,14 +22425,11 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; + var mapper; for (var i = 0; i < typeParameters.length; i++) { - var typeArgNode = typeArguments[i]; - var typeArgument = getTypeFromTypeNode(typeArgNode); - // Do not push on this array! It has a preallocated length - typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable /* so far */) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { @@ -21792,7 +22439,11 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); typeArgumentHeadMessage = headMessage; } - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); } } } @@ -21803,7 +22454,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 187 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 189 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); @@ -21811,7 +22462,7 @@ var ts; // for the argument. In that case, we should check the argument. if (argType === undefined) { argType = arg.kind === 9 /* StringLiteral */ && !reportErrors - ? getStringLiteralType(arg) + ? getStringLiteralTypeForText(arg.text) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } // Use argument expression as error location when reporting errors @@ -21835,10 +22486,10 @@ var ts; */ function getEffectiveCallArguments(node) { var args; - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 172 /* TaggedTemplateExpression */) { var template = node.template; args = [undefined]; - if (template.kind === 183 /* TemplateExpression */) { + if (template.kind === 185 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); @@ -21871,8 +22522,8 @@ var ts; function getEffectiveArgumentCount(node, args, signature) { if (node.kind === 139 /* Decorator */) { switch (node.parent.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; case 141 /* PropertyDeclaration */: @@ -21915,7 +22566,7 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); @@ -21960,7 +22611,7 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } @@ -21984,7 +22635,7 @@ var ts; case 69 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getStringLiteralType(element.name); + return getStringLiteralTypeForText(element.name.text); case 136 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); if (allConstituentTypesHaveKind(nameType, 16777216 /* ESSymbol */)) { @@ -22011,7 +22662,7 @@ var ts; function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator // or its `parameterIndex` for a paramter decorator - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } @@ -22060,7 +22711,7 @@ var ts; if (node.kind === 139 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 172 /* TaggedTemplateExpression */) { return globalTemplateStringsArrayType; } // This is not a synthetic argument, so we return 'undefined' @@ -22073,7 +22724,7 @@ var ts; function getEffectiveArgument(node, args, argIndex) { // For a decorator or the first argument of a tagged template expression we return undefined. if (node.kind === 139 /* Decorator */ || - (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */)) { + (argIndex === 0 && node.kind === 172 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -22086,7 +22737,7 @@ var ts; // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 172 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -22095,7 +22746,7 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 170 /* TaggedTemplateExpression */; + var isTaggedTemplate = node.kind === 172 /* TaggedTemplateExpression */; var isDecorator = node.kind === 139 /* Decorator */; var typeArguments; if (!isTaggedTemplate && !isDecorator) { @@ -22202,7 +22853,8 @@ var ts; } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], /*reportErrors*/ true, headMessage); + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -22260,7 +22912,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -22441,8 +23093,8 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; case 138 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; @@ -22487,13 +23139,13 @@ var ts; // to correctly fill the candidatesOutArray. if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 168 /* CallExpression */) { + if (node.kind === 170 /* CallExpression */) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 169 /* NewExpression */) { + else if (node.kind === 171 /* NewExpression */) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 172 /* TaggedTemplateExpression */) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } else if (node.kind === 139 /* Decorator */) { @@ -22505,6 +23157,13 @@ var ts; } return links.resolvedSignature; } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } /** * Syntactically and semantically checks a call or new expression. * @param node The call/new expression to be checked. @@ -22517,14 +23176,20 @@ var ts; if (node.expression.kind === 95 /* SuperKeyword */) { return voidType; } - if (node.kind === 169 /* NewExpression */) { + if (node.kind === 171 /* NewExpression */) { var declaration = signature.declaration; if (declaration && declaration.kind !== 144 /* Constructor */ && declaration.kind !== 148 /* ConstructSignature */ && declaration.kind !== 153 /* ConstructorType */) { - // When resolved signature is a call signature (and not a construct signature) the result type is any - if (compilerOptions.noImplicitAny) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + var funcSymbol = checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */)) { + return getInferredClassType(funcSymbol); + } + else if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; @@ -22577,7 +23242,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 189 /* OmittedExpression */) { if (element.name.kind === 69 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -22642,7 +23307,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 192 /* Block */) { + if (func.body.kind !== 194 /* Block */) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -22755,38 +23420,53 @@ var ts; }); return aggregatedTypes; } - // TypeScript Specification 1.0 (6.3) - July 2014 - // An explicitly typed function whose return type isn't the Void or the Any type - // must have at least one return statement somewhere in its body. - // An exception to this rule is if the function implementation consists of a single 'throw' statement. + /* + *TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void or the Any type + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; } - // Functions that return 'void' or 'any' don't need any return expressions. + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. if (returnType === voidType || isTypeAny(returnType)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - // also if HasImplicitReturnValue flags is not set this means that all codepaths in function body end with return of throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 /* Block */ || !(func.flags & 524288 /* HasImplicitReturn */)) { + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (ts.nodeIsMissing(func.body) || func.body.kind !== 194 /* Block */ || !(func.flags & 524288 /* HasImplicitReturn */)) { return; } - if (func.flags & 1048576 /* HasExplicitReturn */) { - if (compilerOptions.noImplicitReturns) { - error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { - // This function does not conform to the specification. + var hasExplicitReturn = func.flags & 1048576 /* HasExplicitReturn */; + if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + var inferredReturnType = hasExplicitReturn + ? getReturnTypeOfSignature(getSignatureFromDeclaration(func)) + : voidType; + if (inferredReturnType === voidType || isTypeAny(inferredReturnType)) { + return; + } + } + error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 173 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 175 /* FunctionExpression */) { checkGrammarForGenerator(node); } // The identityMapper object is used to indicate that function expressions are wildcards @@ -22826,6 +23506,7 @@ var ts; } if (!contextChecked) { checkSignatureDeclaration(node); + checkNodeDeferred(node); } } } @@ -22835,19 +23516,16 @@ var ts; } return type; } - function checkFunctionExpressionOrObjectLiteralMethodBody(node) { + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; } - var returnType = node.type && getTypeFromTypeNode(node.type); - var promisedType; - if (returnType && isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - if (returnType && !node.asteriskToken) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + if (!node.asteriskToken) { + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { if (!node.type) { @@ -22858,7 +23536,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 192 /* Block */) { + if (node.body.kind === 194 /* Block */) { checkSourceElement(node.body); } else { @@ -22868,16 +23546,15 @@ var ts; // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. var exprType = checkExpression(node.body); - if (returnType) { + if (returnOrPromisedType) { if (isAsync) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); - checkTypeAssignableTo(awaitedType, promisedType, node.body); + checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } else { - checkTypeAssignableTo(exprType, returnType, node.body); + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } - checkFunctionAndClassExpressionBodies(node.body); } } } @@ -22911,17 +23588,17 @@ var ts; // An identifier expression that references any other kind of entity is classified as a value(and therefore cannot be the target of an assignment). return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 3 /* Variable */) !== 0; } - case 166 /* PropertyAccessExpression */: { + case 168 /* PropertyAccessExpression */: { var symbol = findSymbol(n); // TypeScript 1.0 spec (April 2014): 4.10 // A property access expression is always classified as a reference. // NOTE (not in spec): assignment to enum members should not be allowed return !symbol || symbol === unknownSymbol || (symbol.flags & ~8 /* EnumMember */) !== 0; } - case 167 /* ElementAccessExpression */: + case 169 /* ElementAccessExpression */: // old compiler doesn't check indexed access return true; - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return isReferenceOrErrorExpression(n.expression); default: return false; @@ -22930,11 +23607,11 @@ var ts; function isConstVariableReference(n) { switch (n.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: { + case 168 /* PropertyAccessExpression */: { var symbol = findSymbol(n); return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384 /* Const */) !== 0; } - case 167 /* ElementAccessExpression */: { + case 169 /* ElementAccessExpression */: { var index = n.argumentExpression; var symbol = findSymbol(n.expression); if (symbol && index && index.kind === 9 /* StringLiteral */) { @@ -22944,7 +23621,7 @@ var ts; } return false; } - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return isConstVariableReference(n.expression); default: return false; @@ -23025,8 +23702,8 @@ var ts; } if (type.flags & 49152 /* UnionOrIntersection */) { 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_10 = types; _i < types_10.length; _i++) { + var current = types_10[_i]; if (current.flags & kind) { return true; } @@ -23042,8 +23719,8 @@ var ts; } if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var current = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var current = types_11[_i]; if (!(current.flags & kind)) { return false; } @@ -23090,7 +23767,7 @@ var ts; var properties = node.properties; for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var p = properties_3[_i]; - if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { + if (p.kind === 247 /* PropertyAssignment */ || p.kind === 248 /* ShorthandPropertyAssignment */) { var name_13 = p.name; if (name_13.kind === 136 /* ComputedPropertyName */) { checkComputedPropertyName(name_13); @@ -23105,11 +23782,11 @@ var ts; isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1 /* Number */) || getIndexTypeOfType(sourceType, 0 /* String */); if (type) { - if (p.kind === 246 /* ShorthandPropertyAssignment */) { + if (p.kind === 248 /* ShorthandPropertyAssignment */) { checkDestructuringAssignment(p, type); } else { - // non-shorthand property assignments should always have initializers + // non-shorthand property assignments should always have initializers checkDestructuringAssignment(p.initializer, type); } } @@ -23131,8 +23808,8 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187 /* OmittedExpression */) { - if (e.kind !== 185 /* SpreadElementExpression */) { + if (e.kind !== 189 /* OmittedExpression */) { + if (e.kind !== 187 /* SpreadElementExpression */) { var propName = "" + i; var type = isTypeAny(sourceType) ? sourceType @@ -23157,7 +23834,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 181 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { + if (restExpression.kind === 183 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -23171,7 +23848,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 246 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 248 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -23181,14 +23858,14 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + if (target.kind === 183 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 165 /* ObjectLiteralExpression */) { + if (target.kind === 167 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 164 /* ArrayLiteralExpression */) { + if (target.kind === 166 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); @@ -23205,7 +23882,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 /* EqualsToken */ && (left.kind === 165 /* ObjectLiteralExpression */ || left.kind === 164 /* ArrayLiteralExpression */)) { + if (operator === 56 /* EqualsToken */ && (left.kind === 167 /* ObjectLiteralExpression */ || left.kind === 166 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); @@ -23441,7 +24118,7 @@ var ts; function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { - return getStringLiteralType(node); + return getStringLiteralTypeForText(node.text); } return stringType; } @@ -23527,8 +24204,8 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 167 /* ElementAccessExpression */ && node.parent.expression === node) || + var ok = (node.parent.kind === 168 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 169 /* ElementAccessExpression */ && node.parent.expression === node) || ((node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); @@ -23556,7 +24233,7 @@ var ts; return booleanType; case 8 /* NumericLiteral */: return checkNumericLiteral(node); - case 183 /* TemplateExpression */: + case 185 /* TemplateExpression */: return checkTemplateExpression(node); case 9 /* StringLiteral */: return checkStringLiteralExpression(node); @@ -23564,58 +24241,58 @@ var ts; return stringType; case 10 /* RegularExpressionLiteral */: return globalRegExpType; - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return checkArrayLiteral(node, contextualMapper); - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return checkObjectLiteral(node, contextualMapper); - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 167 /* ElementAccessExpression */: + case 169 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: return checkCallExpression(node); - case 170 /* TaggedTemplateExpression */: + case 172 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return checkExpression(node.expression, contextualMapper); - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: return checkClassExpression(node); - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 176 /* TypeOfExpression */: + case 178 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 173 /* TypeAssertionExpression */: + case 191 /* AsExpression */: return checkAssertion(node); - case 175 /* DeleteExpression */: + case 177 /* DeleteExpression */: return checkDeleteExpression(node); - case 177 /* VoidExpression */: + case 179 /* VoidExpression */: return checkVoidExpression(node); - case 178 /* AwaitExpression */: + case 180 /* AwaitExpression */: return checkAwaitExpression(node); - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 180 /* PostfixUnaryExpression */: + case 182 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return checkBinaryExpression(node, contextualMapper); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return checkConditionalExpression(node, contextualMapper); - case 185 /* SpreadElementExpression */: + case 187 /* SpreadElementExpression */: return checkSpreadElementExpression(node, contextualMapper); - case 187 /* OmittedExpression */: + case 189 /* OmittedExpression */: return undefinedType; - case 184 /* YieldExpression */: + case 186 /* YieldExpression */: return checkYieldExpression(node); - case 240 /* JsxExpression */: + case 242 /* JsxExpression */: return checkJsxExpression(node); - case 233 /* JsxElement */: + case 235 /* JsxElement */: return checkJsxElement(node); - case 234 /* JsxSelfClosingElement */: + case 236 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node); - case 235 /* JsxOpeningElement */: + case 237 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -23627,11 +24304,10 @@ var ts; grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } checkSourceElement(node.constraint); + getConstraintOfTypeParameter(getDeclaredTypeOfTypeParameter(getSymbolOfNode(node))); if (produceDiagnostics) { - checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } - // TODO: Check multiple declarations are identical } function checkParameter(node) { // Grammar checking @@ -23662,8 +24338,8 @@ var ts; return false; } return node.kind === 143 /* MethodDeclaration */ || - node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */; + node.kind === 215 /* FunctionDeclaration */ || + node.kind === 175 /* FunctionExpression */; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { @@ -23677,12 +24353,12 @@ var ts; } return -1; } - function isInLegalTypePredicatePosition(node) { + function isInLegalParameterTypePredicatePosition(node) { switch (node.parent.kind) { - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: case 147 /* CallSignature */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 152 /* FunctionType */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: @@ -23690,12 +24366,24 @@ var ts; } return false; } + function isInLegalThisTypePredicatePosition(node) { + if (isInLegalParameterTypePredicatePosition(node)) { + return true; + } + switch (node.parent.kind) { + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 145 /* GetAccessor */: + return node === node.parent.type; + } + return false; + } function checkSignatureDeclaration(node) { // Grammar checking if (node.kind === 149 /* IndexSignature */) { checkGrammarIndexSignature(node); } - else if (node.kind === 152 /* FunctionType */ || node.kind === 213 /* FunctionDeclaration */ || node.kind === 153 /* ConstructorType */ || + else if (node.kind === 152 /* FunctionType */ || node.kind === 215 /* FunctionDeclaration */ || node.kind === 153 /* ConstructorType */ || node.kind === 147 /* CallSignature */ || node.kind === 144 /* Constructor */ || node.kind === 148 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); @@ -23704,9 +24392,14 @@ var ts; ts.forEach(node.parameters, checkParameter); if (node.type) { if (node.type.kind === 150 /* TypePredicate */) { - var typePredicate = getSignatureFromDeclaration(node).typePredicate; + var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + if (!returnType || !(returnType.flags & 134217728 /* PredicateType */)) { + return; + } + var typePredicate = returnType.predicate; var typePredicateNode = node.type; - if (isInLegalTypePredicatePosition(typePredicateNode)) { + checkSourceElement(typePredicateNode); + if (ts.isIdentifierTypePredicate(typePredicate)) { if (typePredicate.parameterIndex >= 0) { if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); @@ -23722,8 +24415,8 @@ var ts; if (hasReportedError) { break; } - if (param.name.kind === 161 /* ObjectBindingPattern */ || - param.name.kind === 162 /* ArrayBindingPattern */) { + if (param.name.kind === 163 /* ObjectBindingPattern */ || + param.name.kind === 164 /* ArrayBindingPattern */) { (function checkBindingPattern(pattern) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; @@ -23733,8 +24426,8 @@ var ts; hasReportedError = true; break; } - else if (element.name.kind === 162 /* ArrayBindingPattern */ || - element.name.kind === 161 /* ObjectBindingPattern */) { + else if (element.name.kind === 164 /* ArrayBindingPattern */ || + element.name.kind === 163 /* ObjectBindingPattern */) { checkBindingPattern(element.name); } } @@ -23746,9 +24439,6 @@ var ts; } } } - else { - error(typePredicateNode, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); - } } else { checkSourceElement(node.type); @@ -23789,7 +24479,7 @@ var ts; checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 215 /* InterfaceDeclaration */) { + if (node.kind === 217 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind @@ -23839,7 +24529,7 @@ var ts; // Grammar checking checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration - checkFunctionLikeDeclaration(node); + checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. if (node.flags & 128 /* Abstract */ && node.body) { @@ -23866,7 +24556,7 @@ var ts; return; } function isSuperCallExpression(n) { - return n.kind === 168 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; + return n.kind === 170 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; } function containsSuperCallAsComputedPropertyName(n) { return n.name && containsSuperCall(n.name); @@ -23887,7 +24577,7 @@ var ts; if (n.kind === 97 /* ThisKeyword */) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 173 /* FunctionExpression */ && n.kind !== 213 /* FunctionDeclaration */) { + else if (n.kind !== 175 /* FunctionExpression */ && n.kind !== 215 /* FunctionDeclaration */) { ts.forEachChild(n, markThisReferencesAsErrors); } } @@ -23922,7 +24612,7 @@ var ts; var superCallStatement; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 195 /* ExpressionStatement */ && isSuperCallExpression(statement.expression)) { + if (statement.kind === 197 /* ExpressionStatement */ && isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; } @@ -23948,6 +24638,8 @@ var ts; if (produceDiagnostics) { // Grammar checking accessors checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); if (node.kind === 145 /* GetAccessor */) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288 /* HasImplicitReturn */)) { if (node.flags & 1048576 /* HasExplicitReturn */) { @@ -23960,6 +24652,12 @@ var ts; } } } + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 136 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } if (!ts.hasDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. @@ -23982,18 +24680,32 @@ var ts; } getTypeOfAccessors(getSymbolOfNode(node)); } - checkFunctionLikeDeclaration(node); + if (node.parent.kind !== 167 /* ObjectLiteralExpression */) { + checkSourceElement(node.body); + } + else { + checkNodeDeferred(node); + } + } + function checkAccessorDeferred(node) { + checkSourceElement(node.body); } function checkMissingDeclaration(node) { checkDecorators(node); } - function checkTypeArgumentConstraints(typeParameters, typeArguments) { + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var typeArguments; + var mapper; var result = true; for (var i = 0; i < typeParameters.length; i++) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { + if (!typeArguments) { + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + mapper = createTypeMapper(typeParameters, typeArguments); + } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; @@ -24059,7 +24771,7 @@ var ts; var signaturesToCheck; // Unnamed (call\construct) signatures in interfaces are inherited and not shadowed so examining just node symbol won't give complete answer. // Use declaring type to obtain full list of signatures. - if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 215 /* InterfaceDeclaration */) { + if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 217 /* InterfaceDeclaration */) { ts.Debug.assert(signatureDeclarationNode.kind === 147 /* CallSignature */ || signatureDeclarationNode.kind === 148 /* ConstructSignature */); var signatureKind = signatureDeclarationNode.kind === 147 /* CallSignature */ ? 0 /* Call */ : 1 /* Construct */; var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); @@ -24071,7 +24783,7 @@ var ts; } for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { var otherSignature = signaturesToCheck_1[_i]; - if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { + if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature, /*ignoreReturnTypes*/ false)) { return; } } @@ -24081,9 +24793,9 @@ var ts; var flags = ts.getCombinedNodeFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 215 /* InterfaceDeclaration */ && - n.parent.kind !== 214 /* ClassDeclaration */ && - n.parent.kind !== 186 /* ClassExpression */ && + if (n.parent.kind !== 217 /* InterfaceDeclaration */ && + n.parent.kind !== 216 /* ClassDeclaration */ && + n.parent.kind !== 188 /* ClassExpression */ && ts.isInAmbientContext(n)) { if (!(flags & 4 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported @@ -24164,16 +24876,23 @@ var ts; seen = c === node; } }); - if (subsequentNode) { + // We may be here because of some extra junk between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - // the only situation when this is possible (same kind\same name but different symbol) - mixed static and instance class members - ts.Debug.assert(node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */); - ts.Debug.assert((node.flags & 64 /* Static */) !== (subsequentNode.flags & 64 /* Static */)); - var diagnostic = node.flags & 64 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); + var reportError = (node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) && + (node.flags & 64 /* Static */) !== (subsequentNode.flags & 64 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = node.flags & 64 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } return; } else if (ts.nodeIsPresent(subsequentNode.body)) { @@ -24206,7 +24925,7 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 215 /* InterfaceDeclaration */ || node.parent.kind === 155 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 217 /* InterfaceDeclaration */ || node.parent.kind === 155 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -24217,7 +24936,7 @@ var ts; // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one previousDeclaration = undefined; } - if (node.kind === 213 /* FunctionDeclaration */ || node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */ || node.kind === 144 /* Constructor */) { + if (node.kind === 215 /* FunctionDeclaration */ || node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */ || node.kind === 144 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -24288,7 +25007,7 @@ var ts; // The implementation is completely unrelated to the specialized signature, yet we do not check this. for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { var signature = signatures_3[_a]; - if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { + if (!signature.hasStringLiterals && !isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; } @@ -24357,16 +25076,16 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return 2097152 /* ExportType */; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return d.name.kind === 9 /* StringLiteral */ || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ : 4194304 /* ExportNamespace */; - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: var result = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); @@ -24587,6 +25306,8 @@ var ts; error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } + // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. + checkReturnTypeAnnotationAsExpression(node); // Validate the promise constructor type. var promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { @@ -24594,10 +25315,10 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var promiseName = ts.getEntityNameFromTypeNode(node.type); - var root = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, root.text, 107455 /* Value */); + var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); + var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455 /* Value */); if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, getFullyQualifiedName(promiseConstructor)); + error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); return unknownType; } // Get and return the awaited type of the return type. @@ -24614,7 +25335,7 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); @@ -24662,23 +25383,10 @@ var ts; * an expression if it is a type reference to a type with a value declaration. */ function checkTypeAnnotationAsExpression(node) { - switch (node.kind) { - case 141 /* PropertyDeclaration */: - checkTypeNodeAsExpression(node.type); - break; - case 138 /* Parameter */: - checkTypeNodeAsExpression(node.type); - break; - case 143 /* MethodDeclaration */: - checkTypeNodeAsExpression(node.type); - break; - case 145 /* GetAccessor */: - checkTypeNodeAsExpression(node.type); - break; - case 146 /* SetAccessor */: - checkTypeNodeAsExpression(ts.getSetAccessorTypeAnnotationNode(node)); - break; - } + checkTypeNodeAsExpression(node.type); + } + function checkReturnTypeAnnotationAsExpression(node) { + checkTypeNodeAsExpression(node.type); } /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ function checkParameterTypeAnnotationsAsExpressions(node) { @@ -24704,17 +25412,18 @@ var ts; if (compilerOptions.emitDecoratorMetadata) { // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; case 143 /* MethodDeclaration */: - checkParameterTypeAnnotationsAsExpressions(node); - // fall-through - case 146 /* SetAccessor */: case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + checkParameterTypeAnnotationsAsExpressions(node); + checkReturnTypeAnnotationAsExpression(node); + break; case 141 /* PropertyDeclaration */: case 138 /* Parameter */: checkTypeAnnotationAsExpression(node); @@ -24729,13 +25438,13 @@ var ts; } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); + checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); } } - function checkFunctionLikeDeclaration(node) { + function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); var isAsync = ts.isAsyncFunctionLike(node); @@ -24756,7 +25465,13 @@ var ts; // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.getDeclarationOfKind(localSymbol, node.kind); + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.forEach(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(getSourceFile(declaration)) ? + declaration : undefined; }); // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); @@ -24770,13 +25485,9 @@ var ts; } } checkSourceElement(node.body); - if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { - var returnType = getTypeFromTypeNode(node.type); - var promisedType; - if (isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + if (!node.asteriskToken) { + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !node.type) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method @@ -24794,13 +25505,10 @@ var ts; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 192 /* Block */) { + if (node.kind === 194 /* Block */) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 219 /* ModuleBlock */) { - checkFunctionAndClassExpressionBodies(node); - } } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact @@ -24884,12 +25592,12 @@ var ts; return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 218 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (node.kind === 220 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 248 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 250 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -24924,7 +25632,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 211 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 213 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -24934,17 +25642,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 193 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 214 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 195 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 192 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 219 /* ModuleBlock */ || - container.kind === 218 /* ModuleDeclaration */ || - container.kind === 248 /* SourceFile */); + (container.kind === 194 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 221 /* ModuleBlock */ || + container.kind === 220 /* ModuleDeclaration */ || + container.kind === 250 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -25002,7 +25710,7 @@ var ts; checkExpressionCached(node.initializer); } } - if (node.kind === 163 /* BindingElement */) { + if (node.kind === 165 /* BindingElement */) { // check computed properties inside property names of binding elements if (node.propertyName && node.propertyName.kind === 136 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); @@ -25048,7 +25756,7 @@ var ts; if (node.kind !== 141 /* PropertyDeclaration */ && node.kind !== 140 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) { + if (node.kind === 213 /* VariableDeclaration */ || node.kind === 165 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -25071,7 +25779,7 @@ var ts; } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && node.parent.kind === 165 /* ObjectLiteralExpression */) { + if (node.modifiers && node.parent.kind === 167 /* ObjectLiteralExpression */) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -25092,7 +25800,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 194 /* EmptyStatement */) { + if (node.thenStatement.kind === 196 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -25112,12 +25820,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 214 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 214 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -25137,14 +25845,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 214 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); // There may be a destructuring assignment on the left side - if (varExpr.kind === 164 /* ArrayLiteralExpression */ || varExpr.kind === 165 /* ObjectLiteralExpression */) { + if (varExpr.kind === 166 /* ArrayLiteralExpression */ || varExpr.kind === 167 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -25173,7 +25881,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 214 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -25187,7 +25895,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 164 /* ArrayLiteralExpression */ || varExpr.kind === 165 /* ObjectLiteralExpression */) { + if (varExpr.kind === 166 /* ArrayLiteralExpression */ || varExpr.kind === 167 /* 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 */)) { @@ -25383,7 +26091,13 @@ var ts; ts.Debug.assert(languageVersion < 2 /* ES6 */); // 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 = removeTypesFromUnionType(arrayOrStringType, 258 /* StringLike */, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); + var arrayType = arrayOrStringType; + if (arrayOrStringType.flags & 16384 /* Union */) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258 /* StringLike */); })); + } + else if (arrayOrStringType.flags & 258 /* StringLike */) { + arrayType = emptyUnionType; + } var hasStringConstituent = arrayOrStringType !== arrayType; var reportedError = false; if (hasStringConstituent) { @@ -25457,7 +26171,7 @@ var ts; error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { + else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || returnType.flags & 134217728 /* PredicateType */) { if (ts.isAsyncFunctionLike(func)) { var promisedType = getPromisedType(returnType); var awaitedType = checkAwaitedType(exprType, node.expression, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -25494,7 +26208,7 @@ var ts; var expressionTypeIsStringLike = someConstituentTypeHasKind(expressionType, 258 /* StringLike */); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 242 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 244 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -25506,17 +26220,17 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 241 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 243 /* CaseClause */) { var caseClause = clause; // TypeScript 1.0 spec (April 2014):5.9 // In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from the type of the 'switch' expression. var caseType = checkExpression(caseClause.expression); + var expressionTypeIsAssignableToCaseType = // Permit 'number[] | "foo"' to be asserted to 'string'. - if (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258 /* StringLike */)) { - return; - } - if (!isTypeAssignableTo(expressionType, caseType)) { - // check 'expressionType isAssignableTo caseType' failed, try the reversed check and report errors if it fails + (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258 /* StringLike */)) || + isTypeAssignableTo(expressionType, caseType); + if (!expressionTypeIsAssignableToCaseType) { + // 'expressionType is not assignable to caseType', try the reversed check and report errors if it fails checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); } } @@ -25531,7 +26245,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 207 /* LabeledStatement */ && current.label.text === node.label.text) { + if (current.kind === 209 /* LabeledStatement */ && current.label.text === node.label.text) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; @@ -25688,8 +26402,12 @@ var ts; } function checkClassExpression(node) { checkClassLikeDeclaration(node); + checkNodeDeferred(node); return getTypeOfSymbol(getSymbolOfNode(node)); } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + } function checkClassDeclaration(node) { if (!node.name && !(node.flags & 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -25814,7 +26532,7 @@ var ts; // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 128 /* Abstract */))) { - if (derivedClassDecl.kind === 186 /* ClassExpression */) { + if (derivedClassDecl.kind === 188 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -25932,7 +26650,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 215 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 217 /* InterfaceDeclaration */); if (symbol.declarations.length > 1) { if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { error(node.name, ts.Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); @@ -26006,7 +26724,8 @@ var ts; error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); } if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue++; + getNodeLinks(member).enumMemberValue = autoValue; + autoValue++; } } nodeLinks.flags |= 8192 /* EnumValuesComputed */; @@ -26041,7 +26760,7 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; @@ -26052,7 +26771,7 @@ var ts; case 50 /* TildeToken */: return ~value_1; } return undefined; - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -26077,11 +26796,11 @@ var ts; return undefined; case 8 /* NumericLiteral */: return +e.text; - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return evalConstant(e.expression); case 69 /* Identifier */: - case 167 /* ElementAccessExpression */: - case 166 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: + case 168 /* PropertyAccessExpression */: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; @@ -26094,7 +26813,7 @@ var ts; } else { var expression; - if (e.kind === 167 /* ElementAccessExpression */) { + if (e.kind === 169 /* ElementAccessExpression */) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9 /* StringLiteral */) { return undefined; @@ -26112,7 +26831,7 @@ var ts; if (current.kind === 69 /* Identifier */) { break; } - else if (current.kind === 166 /* PropertyAccessExpression */) { + else if (current.kind === 168 /* PropertyAccessExpression */) { current = current.expression; } else { @@ -26183,7 +26902,7 @@ var ts; var seenEnumMissingInitialInitializer = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 217 /* EnumDeclaration */) { + if (declaration.kind !== 219 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -26206,8 +26925,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 214 /* ClassDeclaration */ || - (declaration.kind === 213 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 216 /* ClassDeclaration */ || + (declaration.kind === 215 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -26263,7 +26982,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 214 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 216 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -26286,7 +27005,7 @@ var ts; if (node.kind === 135 /* QualifiedName */) { node = node.left; } - else if (node.kind === 166 /* PropertyAccessExpression */) { + else if (node.kind === 168 /* PropertyAccessExpression */) { node = node.expression; } else { @@ -26302,9 +27021,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 219 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; - if (node.parent.kind !== 248 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 228 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 221 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; + if (node.parent.kind !== 250 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 230 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -26327,7 +27046,7 @@ var ts; (symbol.flags & 793056 /* Type */ ? 793056 /* Type */ : 0) | (symbol.flags & 1536 /* Namespace */ ? 1536 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 230 /* ExportSpecifier */ ? + var message = node.kind === 232 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -26354,7 +27073,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 226 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -26411,8 +27130,8 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 219 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; - if (node.parent.kind !== 248 /* SourceFile */ && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 221 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; + if (node.parent.kind !== 250 /* SourceFile */ && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -26426,7 +27145,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 248 /* SourceFile */ && node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 218 /* ModuleDeclaration */) { + if (node.parent.kind !== 250 /* SourceFile */ && node.parent.kind !== 221 /* ModuleBlock */ && node.parent.kind !== 220 /* ModuleDeclaration */) { return grammarErrorOnFirstToken(node, errorMessage); } } @@ -26441,8 +27160,8 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 248 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 218 /* ModuleDeclaration */ && container.name.kind === 69 /* Identifier */) { + var container = node.parent.kind === 250 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 220 /* ModuleDeclaration */ && container.name.kind === 69 /* Identifier */) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } @@ -26468,15 +27187,6 @@ var ts; } } } - function getModuleStatements(node) { - if (node.kind === 248 /* SourceFile */) { - return node.statements; - } - if (node.kind === 218 /* ModuleDeclaration */ && node.body.kind === 219 /* ModuleBlock */) { - return node.body.statements; - } - return emptyArray; - } function hasExportedMembers(moduleSymbol) { for (var id in moduleSymbol.exports) { if (id !== "export=") { @@ -26494,13 +27204,43 @@ var ts; var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } + // Checks for export * conflicts + var exports = getExportsOfModule(moduleSymbol); + for (var id in exports) { + if (id === "__export") { + continue; + } + 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 */)) && (flags & 524288 /* TypeAlias */ ? declarations.length - 1 : declarations.length) > 1) { + var exportedDeclarations = ts.filter(declarations, isNotOverload); + if (exportedDeclarations.length > 1) { + for (var _i = 0, exportedDeclarations_1 = exportedDeclarations; _i < exportedDeclarations_1.length; _i++) { + var declaration = exportedDeclarations_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); + } + } + } + } links.exportsChecked = true; } + function isNotOverload(declaration) { + return declaration.kind !== 215 /* FunctionDeclaration */ || !!declaration.body; + } } function checkTypePredicate(node) { - if (!isInLegalTypePredicatePosition(node)) { + var parameterName = node.parameterName; + if (parameterName.kind === 69 /* Identifier */ && !isInLegalParameterTypePredicatePosition(node)) { error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); } + else if (parameterName.kind === 161 /* ThisType */) { + if (!isInLegalThisTypePredicatePosition(node)) { + error(node, ts.Diagnostics.A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_return_type_positions_for_functions_and_methods); + } + else { + getTypeFromThisTypeNode(parameterName); + } + } } function checkSourceElement(node) { if (!node) { @@ -26511,10 +27251,10 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessivly // hitting the cancellation token on every node we check. switch (kind) { - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 220 /* ModuleDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 215 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -26558,71 +27298,71 @@ var ts; return checkUnionOrIntersectionType(node); case 160 /* ParenthesizedType */: return checkSourceElement(node.type); - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 194 /* Block */: + case 221 /* ModuleBlock */: return checkBlock(node); - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return checkVariableStatement(node); - case 195 /* ExpressionStatement */: + case 197 /* ExpressionStatement */: return checkExpressionStatement(node); - case 196 /* IfStatement */: + case 198 /* IfStatement */: return checkIfStatement(node); - case 197 /* DoStatement */: + case 199 /* DoStatement */: return checkDoStatement(node); - case 198 /* WhileStatement */: + case 200 /* WhileStatement */: return checkWhileStatement(node); - case 199 /* ForStatement */: + case 201 /* ForStatement */: return checkForStatement(node); - case 200 /* ForInStatement */: + case 202 /* ForInStatement */: return checkForInStatement(node); - case 201 /* ForOfStatement */: + case 203 /* ForOfStatement */: return checkForOfStatement(node); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 204 /* ContinueStatement */: + case 205 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 204 /* ReturnStatement */: + case 206 /* ReturnStatement */: return checkReturnStatement(node); - case 205 /* WithStatement */: + case 207 /* WithStatement */: return checkWithStatement(node); - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: return checkSwitchStatement(node); - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: return checkLabeledStatement(node); - case 208 /* ThrowStatement */: + case 210 /* ThrowStatement */: return checkThrowStatement(node); - case 209 /* TryStatement */: + case 211 /* TryStatement */: return checkTryStatement(node); - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 163 /* BindingElement */: + case 165 /* BindingElement */: return checkBindingElement(node); - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: return checkClassDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 216 /* TypeAliasDeclaration */: + case 218 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: return checkImportDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return checkExportDeclaration(node); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return checkExportAssignment(node); - case 194 /* EmptyStatement */: + case 196 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 210 /* DebuggerStatement */: + case 212 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 231 /* MissingDeclaration */: + case 233 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -26635,102 +27375,29 @@ var ts; // Here, performing a full type check of the body of the function expression whilst in the process of // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. - function checkFunctionAndClassExpressionBodies(node) { - switch (node.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - checkFunctionExpressionOrObjectLiteralMethodBody(node); - break; - case 186 /* ClassExpression */: - ts.forEach(node.members, checkSourceElement); - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - if (ts.isObjectLiteralMethod(node)) { - checkFunctionExpressionOrObjectLiteralMethodBody(node); - } - break; - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - break; - case 205 /* WithStatement */: - checkFunctionAndClassExpressionBodies(node.expression); - break; - case 139 /* Decorator */: - case 138 /* Parameter */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 163 /* BindingElement */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 245 /* PropertyAssignment */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 170 /* TaggedTemplateExpression */: - case 183 /* TemplateExpression */: - case 190 /* TemplateSpan */: - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: - case 172 /* ParenthesizedExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 178 /* AwaitExpression */: - case 175 /* DeleteExpression */: - case 179 /* PrefixUnaryExpression */: - case 180 /* PostfixUnaryExpression */: - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 184 /* YieldExpression */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 193 /* VariableStatement */: - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 220 /* CaseBlock */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: - case 211 /* VariableDeclaration */: - case 212 /* VariableDeclarationList */: - case 214 /* ClassDeclaration */: - case 243 /* HeritageClause */: - case 188 /* ExpressionWithTypeArguments */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 227 /* ExportAssignment */: - case 248 /* SourceFile */: - case 240 /* JsxExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - case 235 /* JsxOpeningElement */: - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + checkAccessorDeferred(node); + break; + case 188 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + } } } function checkSourceFile(node) { @@ -26756,9 +27423,12 @@ var ts; emitExtends = false; emitDecorate = false; emitParam = false; + emitAwaiter = false; potentialThisCollisions.length = 0; + deferredNodes = []; ts.forEach(node.statements, checkSourceElement); - checkFunctionAndClassExpressionBodies(node); + checkDeferredNodes(); + deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -26818,7 +27488,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 205 /* WithStatement */ && node.parent.statement === node) { + if (node.parent.kind === 207 /* WithStatement */ && node.parent.statement === node) { return true; } node = node.parent; @@ -26841,25 +27511,25 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); break; - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } // fall through; this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -26868,7 +27538,7 @@ var ts; copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; - case 173 /* FunctionExpression */: + case 175 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -26918,10 +27588,10 @@ var ts; function isTypeDeclaration(node) { switch (node.kind) { case 137 /* TypeParameter */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 219 /* EnumDeclaration */: return true; } } @@ -26935,19 +27605,19 @@ var ts; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 166 /* PropertyAccessExpression */) { + while (node.parent && node.parent.kind === 168 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 188 /* ExpressionWithTypeArguments */; + return node.parent && node.parent.kind === 190 /* ExpressionWithTypeArguments */; } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { while (nodeOnRightSide.parent.kind === 135 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 221 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 223 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 227 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 229 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -26959,11 +27629,11 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 227 /* ExportAssignment */) { + if (entityName.parent.kind === 229 /* ExportAssignment */) { return resolveEntityName(entityName, /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 166 /* PropertyAccessExpression */) { + if (entityName.kind !== 168 /* PropertyAccessExpression */) { if (isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); @@ -26975,7 +27645,7 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 188 /* ExpressionWithTypeArguments */) { + if (entityName.parent.kind === 190 /* ExpressionWithTypeArguments */) { meaning = 793056 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -26988,9 +27658,9 @@ var ts; meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if ((entityName.parent.kind === 235 /* JsxOpeningElement */) || - (entityName.parent.kind === 234 /* JsxSelfClosingElement */) || - (entityName.parent.kind === 237 /* JsxClosingElement */)) { + else if ((entityName.parent.kind === 237 /* JsxOpeningElement */) || + (entityName.parent.kind === 236 /* JsxSelfClosingElement */) || + (entityName.parent.kind === 239 /* JsxClosingElement */)) { return getJsxElementTagSymbol(entityName.parent); } else if (ts.isExpression(entityName)) { @@ -27004,7 +27674,7 @@ var ts; var meaning = 107455 /* Value */ | 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 166 /* PropertyAccessExpression */) { + else if (entityName.kind === 168 /* PropertyAccessExpression */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); @@ -27026,7 +27696,7 @@ var ts; meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if (entityName.parent.kind === 238 /* JsxAttribute */) { + else if (entityName.parent.kind === 240 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } if (entityName.parent.kind === 150 /* TypePredicate */) { @@ -27046,12 +27716,12 @@ var ts; } if (node.kind === 69 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 227 /* ExportAssignment */ + return node.parent.kind === 229 /* ExportAssignment */ ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } - else if (node.parent.kind === 163 /* BindingElement */ && - node.parent.parent.kind === 161 /* ObjectBindingPattern */ && + else if (node.parent.kind === 165 /* BindingElement */ && + node.parent.parent.kind === 163 /* ObjectBindingPattern */ && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -27062,13 +27732,15 @@ var ts; } switch (node.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: case 135 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; + case 161 /* ThisType */: + return getTypeFromTypeNode(node).symbol; case 121 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; @@ -27080,14 +27752,14 @@ var ts; // External module name in an import declaration if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 222 /* ImportDeclaration */ || node.parent.kind === 228 /* ExportDeclaration */) && + ((node.parent.kind === 224 /* ImportDeclaration */ || node.parent.kind === 230 /* ExportDeclaration */) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } // Fall through case 8 /* NumericLiteral */: // index access - if (node.parent.kind === 167 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { + if (node.parent.kind === 169 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -27104,7 +27776,7 @@ var ts; // The function returns a value symbol of an identifier in the short-hand property assignment. // This is necessary as an identifier in short-hand property assignment can contains two meaning: // property name and property value. - if (location && location.kind === 246 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 248 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 107455 /* Value */); } return undefined; @@ -27207,6 +27879,30 @@ var ts; function isArgumentsLocalBinding(node) { return getReferencedValueSymbol(node) === argumentsSymbol; } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol) { + // module not found - be conservative + return true; + } + var hasExportAssignment = getExportAssignmentSymbol(moduleSymbol) !== undefined; + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455 /* Value */) + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455 /* Value */); + } + } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. function getReferencedExportContainer(node) { @@ -27224,11 +27920,11 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 248 /* SourceFile */) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 250 /* SourceFile */) { return parentSymbol.valueDeclaration; } for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 218 /* ModuleDeclaration */ || n.kind === 217 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { + if ((n.kind === 220 /* ModuleDeclaration */ || n.kind === 219 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { return n; } } @@ -27243,11 +27939,11 @@ var ts; } function isStatementWithLocals(node) { switch (node.kind) { - case 192 /* Block */: - case 220 /* CaseBlock */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 194 /* Block */: + case 222 /* CaseBlock */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: return true; } return false; @@ -27277,22 +27973,22 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 223 /* ImportEqualsDeclaration */: + case 225 /* ImportClause */: + case 226 /* NamespaceImport */: + case 228 /* ImportSpecifier */: + case 232 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node)); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return node.expression && node.expression.kind === 69 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 248 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 250 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -27354,7 +28050,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 247 /* EnumMember */) { + if (node.kind === 249 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -27446,17 +28142,6 @@ var ts; var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } - function instantiateSingleCallFunctionType(functionType, typeArguments) { - if (functionType === unknownType) { - return unknownType; - } - var signature = getSingleCallSignature(functionType); - if (!signature) { - return unknownType; - } - var instantiatedSignature = getSignatureInstantiation(signature, typeArguments); - return getOrCreateTypeFromSignature(instantiatedSignature); - } function createResolver() { return { getReferencedExportContainer: getReferencedExportContainer, @@ -27480,6 +28165,7 @@ var ts; getReferencedValueDeclaration: getReferencedValueDeclaration, getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, isArgumentsLocalBinding: isArgumentsLocalBinding, getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration }; @@ -27490,7 +28176,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 248 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 250 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -27503,10 +28189,11 @@ var ts; mergeSymbolTable(globals, file.locals); } }); + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); getSymbolLinks(unknownSymbol).type = unknownType; - globals[undefinedSymbol.name] = undefinedSymbol; // Initialize special types globalArrayType = getGlobalType("Array", /*arity*/ 1); globalObjectType = getGlobalType("Object"); @@ -27575,7 +28262,12 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + if (node.kind === 143 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } } else if (node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); @@ -27595,30 +28287,30 @@ var ts; case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 149 /* IndexSignature */: - case 218 /* ModuleDeclaration */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: - case 227 /* ExportAssignment */: + case 220 /* ModuleDeclaration */: + case 224 /* ImportDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 230 /* ExportDeclaration */: + case 229 /* ExportAssignment */: case 138 /* Parameter */: break; - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118 /* AsyncKeyword */) && - node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + node.parent.kind !== 221 /* ModuleBlock */ && node.parent.kind !== 250 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 193 /* VariableStatement */: - case 216 /* TypeAliasDeclaration */: - if (node.modifiers && node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 195 /* VariableStatement */: + case 218 /* TypeAliasDeclaration */: + if (node.modifiers && node.parent.kind !== 221 /* ModuleBlock */ && node.parent.kind !== 250 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74 /* ConstKeyword */) && - node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + node.parent.kind !== 221 /* ModuleBlock */ && node.parent.kind !== 250 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; @@ -27633,6 +28325,11 @@ var ts; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; switch (modifier.kind) { + case 74 /* ConstKeyword */: + if (node.kind !== 219 /* EnumDeclaration */ && node.parent.kind === 216 /* ClassDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74 /* ConstKeyword */)); + } + break; case 112 /* PublicKeyword */: case 111 /* ProtectedKeyword */: case 110 /* PrivateKeyword */: @@ -27657,7 +28354,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { + else if (node.parent.kind === 221 /* ModuleBlock */ || node.parent.kind === 250 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } else if (flags & 128 /* Abstract */) { @@ -27677,7 +28374,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { + else if (node.parent.kind === 221 /* ModuleBlock */ || node.parent.kind === 250 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); } else if (node.kind === 138 /* Parameter */) { @@ -27702,7 +28399,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 216 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } else if (node.kind === 138 /* Parameter */) { @@ -27717,13 +28414,13 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 216 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } else if (node.kind === 138 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219 /* ModuleBlock */) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 221 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 4 /* Ambient */; @@ -27733,11 +28430,11 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 214 /* ClassDeclaration */) { + if (node.kind !== 216 /* ClassDeclaration */) { if (node.kind !== 143 /* MethodDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); } - if (!(node.parent.kind === 214 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { + if (!(node.parent.kind === 216 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 64 /* Static */) { @@ -27782,7 +28479,7 @@ var ts; } return; } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && flags & 4 /* Ambient */) { + else if ((node.kind === 224 /* ImportDeclaration */ || node.kind === 223 /* ImportEqualsDeclaration */) && flags & 4 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 138 /* Parameter */ && (flags & 56 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { @@ -27798,9 +28495,9 @@ var ts; } switch (node.kind) { case 143 /* MethodDeclaration */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: if (!node.asteriskToken) { return false; } @@ -27866,7 +28563,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 174 /* ArrowFunction */) { + if (node.kind === 176 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -27934,7 +28631,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { var arg = args_1[_i]; - if (arg.kind === 187 /* OmittedExpression */) { + if (arg.kind === 189 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -28012,14 +28709,14 @@ var ts; return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 181 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { + if (computedPropertyName.expression.kind === 183 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */ || + ts.Debug.assert(node.kind === 215 /* FunctionDeclaration */ || + node.kind === 175 /* FunctionExpression */ || node.kind === 143 /* MethodDeclaration */); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); @@ -28043,20 +28740,25 @@ var ts; var GetAccessor = 2; var SetAccesor = 4; var GetOrSetAccessor = GetAccessor | SetAccesor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; + var _loop_1 = function(prop) { var name_16 = prop.name; - if (prop.kind === 187 /* OmittedExpression */ || + if (prop.kind === 189 /* OmittedExpression */ || name_16.kind === 136 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name_16); - continue; + return "continue"; } - if (prop.kind === 246 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 248 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; } + // Modifiers are never allowed on properties except for 'async' on a method declaration + ts.forEach(prop.modifiers, function (mod) { + if (mod.kind !== 118 /* AsyncKeyword */ || prop.kind !== 143 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + }); // ECMA-262 11.1.5 Object Initialiser // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and @@ -28066,7 +28768,7 @@ var ts; // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; - if (prop.kind === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */) { + if (prop.kind === 247 /* PropertyAssignment */ || prop.kind === 248 /* ShorthandPropertyAssignment */) { // Grammar checking for computedPropertName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name_16.kind === 8 /* NumericLiteral */) { @@ -28092,27 +28794,33 @@ var ts; else { var existingKind = seen[name_16.text]; if (currentKind === Property && existingKind === Property) { - continue; + return "continue"; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[name_16.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return { value: grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return { value: grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } + }; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var state_1 = _loop_1(prop); + if (typeof state_1 === "object") return state_1.value + if (state_1 === "continue") continue; } } function checkGrammarJsxElement(node) { var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 239 /* JsxSpreadAttribute */) { + if (attr.kind === 241 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; @@ -28124,7 +28832,7 @@ var ts; return grammarErrorOnNode(name_17, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 240 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 242 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -28133,24 +28841,35 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 212 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 214 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { - if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 202 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } - var firstDeclaration = variableList.declarations[0]; + var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 202 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 202 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -28211,7 +28930,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 165 /* ObjectLiteralExpression */) { + if (node.parent.kind === 167 /* ObjectLiteralExpression */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -28235,7 +28954,7 @@ var ts; return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); } } - else if (node.parent.kind === 215 /* InterfaceDeclaration */) { + else if (node.parent.kind === 217 /* InterfaceDeclaration */) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); } else if (node.parent.kind === 155 /* TypeLiteral */) { @@ -28249,11 +28968,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: if (node.label && current.label.text === node.label.text) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 202 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 204 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -28261,8 +28980,8 @@ var ts; return false; } break; - case 206 /* SwitchStatement */: - if (node.kind === 203 /* BreakStatement */ && !node.label) { + case 208 /* SwitchStatement */: + if (node.kind === 205 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -28277,13 +28996,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 203 /* BreakStatement */ + var message = node.kind === 205 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 203 /* BreakStatement */ + var message = node.kind === 205 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -28295,7 +29014,7 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } - if (node.name.kind === 162 /* ArrayBindingPattern */ || node.name.kind === 161 /* ObjectBindingPattern */) { + if (node.name.kind === 164 /* ArrayBindingPattern */ || node.name.kind === 163 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -28305,7 +29024,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 200 /* ForInStatement */ && node.parent.parent.kind !== 201 /* ForOfStatement */) { + if (node.parent.parent.kind !== 202 /* ForInStatement */ && node.parent.parent.kind !== 203 /* ForOfStatement */) { if (ts.isInAmbientContext(node)) { if (node.initializer) { // Error on equals token which immediate precedes the initializer @@ -28322,7 +29041,7 @@ var ts; } } } - var checkLetConstNames = languageVersion >= 2 /* ES6 */ && (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding @@ -28333,7 +29052,7 @@ var ts; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 69 /* Identifier */) { - if (name.text === "let") { + if (name.originalKeywordKind === 108 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -28341,7 +29060,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 189 /* OmittedExpression */) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -28358,15 +29077,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 198 /* IfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: + case 207 /* WithStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: return false; - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -28381,23 +29100,6 @@ var ts; } } } - function isIntegerLiteral(expression) { - if (expression.kind === 179 /* PrefixUnaryExpression */) { - var unaryExpression = expression; - if (unaryExpression.operator === 35 /* PlusToken */ || unaryExpression.operator === 36 /* MinusToken */) { - expression = unaryExpression.operand; - } - } - if (expression.kind === 8 /* NumericLiteral */) { - // Allows for scientific notation since literalExpression.text was formed by - // coercing a number to a string. Sometimes this coercion can yield a string - // in scientific notation. - // We also don't need special logic for hex because a hex integer is converted - // to decimal when it is coerced. - return /^[0-9]+([eE]\+?[0-9]+)?$/.test(expression.text); - } - return false; - } function hasParseDiagnostics(sourceFile) { return sourceFile.parseDiagnostics.length > 0; } @@ -28422,10 +29124,6 @@ var ts; return true; } } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 /* Identifier */ && - (node.text === "eval" || node.text === "arguments"); - } function checkGrammarConstructorTypeParameters(node) { if (node.typeParameters) { return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); @@ -28443,15 +29141,21 @@ var ts; return true; } } - else if (node.parent.kind === 215 /* InterfaceDeclaration */) { + else if (node.parent.kind === 217 /* InterfaceDeclaration */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } } else if (node.parent.kind === 155 /* TypeLiteral */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } } if (ts.isInAmbientContext(node) && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); @@ -28470,12 +29174,12 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 215 /* InterfaceDeclaration */ || - node.kind === 216 /* TypeAliasDeclaration */ || - node.kind === 222 /* ImportDeclaration */ || - node.kind === 221 /* ImportEqualsDeclaration */ || - node.kind === 228 /* ExportDeclaration */ || - node.kind === 227 /* ExportAssignment */ || + if (node.kind === 217 /* InterfaceDeclaration */ || + node.kind === 218 /* TypeAliasDeclaration */ || + node.kind === 224 /* ImportDeclaration */ || + node.kind === 223 /* ImportEqualsDeclaration */ || + node.kind === 230 /* ExportDeclaration */ || + node.kind === 229 /* ExportAssignment */ || (node.flags & 4 /* Ambient */) || (node.flags & (2 /* Export */ | 512 /* Default */))) { return false; @@ -28485,7 +29189,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 193 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 195 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -28511,7 +29215,7 @@ var ts; // to prevent noisyness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 192 /* Block */ || node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { + if (node.parent.kind === 194 /* Block */ || node.parent.kind === 221 /* ModuleBlock */ || node.parent.kind === 250 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -28536,21 +29240,293 @@ var ts; return true; } } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); /// /* @internal */ var ts; +(function (ts) { + var nullSourceMapWriter; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitStart: function (range) { }, + emitEnd: function (range) { }, + emitPos: function (pos) { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; }, + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + var currentSourceFile; + var sourceMapDir; // The directory in which sourcemap will be + // Current source map file and its index in the sources list + var sourceMapSourceIndex; + // Last recorded and encoded spans + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan; + var lastEncodedNameIndex; + // Source map data + var sourceMapData; + return { + getSourceMapData: function () { return sourceMapData; }, + setSourceFile: setSourceFile, + emitPos: emitPos, + emitStart: emitStart, + emitEnd: emitEnd, + getText: getText, + getSourceMappingURL: getSourceMappingURL, + initialize: initialize, + reset: reset + }; + function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (sourceMapData) { + reset(); + } + currentSourceFile = undefined; + // Current source map file and its index in the sources list + sourceMapSourceIndex = -1; + // Last recorded and encoded spans + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + lastEncodedNameIndex = 0; + // Initialize source map data + sourceMapData = { + sourceMapFilePath: sourceMapFilePath, + jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, + sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, + sourceMapDecodedMappings: [] + }; + // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the + // relative paths of the sources list in the sourcemap + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (!isBundledEmit) { + ts.Debug.assert(sourceFiles.length === 1); + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); + } + } + function reset() { + currentSourceFile = undefined; + sourceMapDir = undefined; + sourceMapSourceIndex = undefined; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = undefined; + lastEncodedNameIndex = undefined; + sourceMapData = undefined; + } + // Encoding for sourcemap span + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + // Line/Comma delimiters + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + // Emit comma to separate the entry + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + // Emit line delimiters + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + // 1. Relative Column 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + // 2. Relative sourceIndex + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + // 3. Relative sourceLine 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + // 4. Relative sourceColumn 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + // 5. Relative namePosition 0 based + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + } + function emitPos(pos) { + if (pos === -1) { + return; + } + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + // Convert the location to be one-based. + sourceLinePos.line++; + sourceLinePos.character++; + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + // If this location wasn't recorded or the location in source is going backwards, record the span + if (!lastRecordedSourceMapSpan || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || + (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && + (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || + (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + // Encode the last recordedSpan before assigning new + encodeLastRecordedSourceMapSpan(); + // New span + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + sourceIndex: sourceMapSourceIndex + }; + } + else { + // Take the new pos instead since there is no change in emittedLine and column since last location + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + } + function emitStart(range) { + var rangeHasDecorators = !!range.decorators; + emitPos(range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1); + } + function emitEnd(range) { + emitPos(range.end); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + // Add the file to tsFilePaths + // If sourceroot option: Use the relative path corresponding to the common directory path + // otherwise source locations relative to map file location + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + if (sourceMapSourceIndex === -1) { + sourceMapSourceIndex = sourceMapData.sourceMapSources.length; + sourceMapData.sourceMapSources.push(source); + // The one that can be used from program to get the actual source file + sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + if (compilerOptions.inlineSources) { + sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + } + } + } + function getText() { + encodeLastRecordedSourceMapSpan(); + return ts.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent + }); + } + function getSourceMappingURL() { + if (compilerOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var base64SourceMapText = ts.convertToBase64(getText()); + return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; + } + else { + return sourceMapData.jsSourceMappingURL; + } + } + } + ts.createSourceMapWriter = createSourceMapWriter; + var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function base64FormatEncode(inValue) { + if (inValue < 64) { + return base64Chars.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + function base64VLQFormatEncode(inValue) { + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + // Encode 5 bits at a time starting from least significant bits + var encodedStr = ""; + do { + var currentDigit = inValue & 31; // 11111 + inValue = inValue >> 5; + if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } +})(ts || (ts = {})); +/// +/* @internal */ +var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var diagnostics = []; - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); - emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); - return diagnostics; + var declarationDiagnostics = ts.createDiagnosticCollection(); + ts.forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); + return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName); + function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { + var declarationFilePath = _a.declarationFilePath; + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -28568,103 +29544,79 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare = !root; + var noDeclare; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. // Collecting this separately because reference paths need to be first thing in the declaration file // and we could be collecting these paths from multiple files into single one with --out option var referencePathsOutput = ""; - if (root) { - // Emitting just a single file, so emit references in this file only + // Emit references corresponding to each file + var emittedReferencedFiles = []; + var addedGlobalFileReference = false; + var allSourcesModuleElementDeclarationEmitInfo = []; + ts.forEach(sourceFiles, function (sourceFile) { + // Dont emit for javascript file + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + // Check what references need to be added if (!compilerOptions.noResolve) { - var addedGlobalFileReference = false; - ts.forEach(root.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); - // All the references that are not going to be part of same file - if (referencedFile && ((referencedFile.flags & 4096 /* DeclarationFile */) || - ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || - !addedGlobalFileReference)) { - writeReferencePath(referencedFile); - if (!ts.isExternalModuleOrDeclarationFile(referencedFile)) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + // Emit reference in dts, if the file reference was not already emitted + if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { + // Add a reference to generated dts file, + // global file reference is added only + // - if it is not bundled emit (because otherwise it would be self reference) + // - and it is not already added + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } + emittedReferencedFiles.push(referencedFile); } }); } - emitSourceFile(root); + if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { + noDeclare = false; + emitSourceFile(sourceFile); + } + else if (ts.isExternalModule(sourceFile)) { + noDeclare = true; + write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); + writeLine(); + increaseIndent(); + emitSourceFile(sourceFile); + decreaseIndent(); + write("}"); + writeLine(); + } // create asynchronous output for the importDeclarations if (moduleElementDeclarationEmitInfo.length) { var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222 /* ImportDeclaration */); + if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { + ts.Debug.assert(aliasEmitInfo.node.kind === 224 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0); + ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + increaseIndent(); + } writeImportDeclaration(aliasEmitInfo.node); aliasEmitInfo.asynchronousOutput = writer.getText(); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + decreaseIndent(); + } } }); setWriter(oldWriter); + allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); + moduleElementDeclarationEmitInfo = []; } - } - else { - // Emit references corresponding to this file - var emittedReferencedFiles = []; - var prevModuleElementDeclarationEmitInfo = []; - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!ts.isDeclarationFile(sourceFile)) { - // Check what references need to be added - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - // If the reference file is a declaration file, emit that reference - if (referencedFile && (ts.isDeclarationFile(referencedFile) && - !ts.contains(emittedReferencedFiles, referencedFile))) { - writeReferencePath(referencedFile); - emittedReferencedFiles.push(referencedFile); - } - }); - } - } - if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) { - noDeclare = false; - emitSourceFile(sourceFile); - } - else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; - write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - write("}"); - writeLine(); - // create asynchronous output for the importDeclarations - if (moduleElementDeclarationEmitInfo.length) { - var oldWriter = writer; - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222 /* ImportDeclaration */); - createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 1); - increaseIndent(); - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - decreaseIndent(); - } - }); - setWriter(oldWriter); - } - prevModuleElementDeclarationEmitInfo = prevModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - }); - moduleElementDeclarationEmitInfo = moduleElementDeclarationEmitInfo.concat(prevModuleElementDeclarationEmitInfo); - } + }); return { reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: moduleElementDeclarationEmitInfo, + moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), referencePathsOutput: referencePathsOutput }; @@ -28707,10 +29659,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 211 /* VariableDeclaration */) { + if (declaration.kind === 213 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 225 /* NamedImports */ || declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 223 /* ImportClause */) { + else if (declaration.kind === 227 /* NamedImports */ || declaration.kind === 228 /* ImportSpecifier */ || declaration.kind === 225 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -28728,7 +29680,7 @@ var ts; // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, // we would write alias foo declaration when we visit it since it would now be marked as visible if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 222 /* ImportDeclaration */) { + if (moduleElementEmitInfo.node.kind === 224 /* ImportDeclaration */) { // we have to create asynchronous output only after we have collected complete information // because it is possible to enable multiple bindings as asynchronously visible moduleElementEmitInfo.isVisible = true; @@ -28738,12 +29690,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 220 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 220 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -28766,10 +29718,10 @@ var ts; var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); if (errorInfo) { if (errorInfo.typeName) { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); } else { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); } } } @@ -28779,7 +29731,8 @@ var ts; } function reportInaccessibleThisError() { if (errorNameNode) { - diagnostics.push(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { @@ -28850,10 +29803,10 @@ var ts; case 120 /* BooleanKeyword */: case 131 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 97 /* ThisKeyword */: - case 9 /* StringLiteral */: + case 161 /* ThisType */: + case 162 /* StringLiteralType */: return writeTextOfNode(currentText, type); - case 188 /* ExpressionWithTypeArguments */: + case 190 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); case 151 /* TypeReference */: return emitTypeReference(type); @@ -28896,13 +29849,13 @@ var ts; function emitEntityName(entityName) { var visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 221 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); + entityName.parent.kind === 223 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 166 /* PropertyAccessExpression */); + ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 168 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -28980,7 +29933,8 @@ var ts; } var count = 0; while (true) { - var name_18 = baseName + "_" + (++count); + count++; + var name_18 = baseName + "_" + count; if (!ts.hasProperty(currentIdentifiers, name_18)) { return name_18; } @@ -29026,10 +29980,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 221 /* ImportEqualsDeclaration */ || - (node.parent.kind === 248 /* SourceFile */ && isCurrentFileExternalModule)) { + else if (node.kind === 223 /* ImportEqualsDeclaration */ || + (node.parent.kind === 250 /* SourceFile */ && isCurrentFileExternalModule)) { var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248 /* SourceFile */) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 250 /* SourceFile */) { // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, @@ -29039,7 +29993,7 @@ var ts; }); } else { - if (node.kind === 222 /* ImportDeclaration */) { + if (node.kind === 224 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -29057,23 +30011,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return writeVariableStatement(node); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: return writeClassDeclaration(node); - case 216 /* TypeAliasDeclaration */: + case 218 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -29081,7 +30035,7 @@ var ts; } function emitModuleElementDeclarationFlags(node) { // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent.kind === 248 /* SourceFile */) { + if (node.parent.kind === 250 /* SourceFile */) { // If the node is exported if (node.flags & 2 /* Export */) { write("export "); @@ -29089,7 +30043,7 @@ var ts; if (node.flags & 512 /* Default */) { write("default "); } - else if (node.kind !== 215 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 217 /* InterfaceDeclaration */ && !noDeclare) { write("declare "); } } @@ -29124,7 +30078,7 @@ var ts; } else { write("require("); - writeTextOfNode(currentText, ts.getExternalModuleImportEqualsDeclarationExpression(node)); + emitExternalModuleSpecifier(node); write(");"); } writer.writeLine(); @@ -29138,7 +30092,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 224 /* NamespaceImport */) { + if (namedBindings.kind === 226 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -29166,7 +30120,7 @@ var ts; // If the default binding was emitted, write the separated write(", "); } - if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 226 /* NamespaceImport */) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -29178,13 +30132,22 @@ var ts; } write(" from "); } - emitExternalModuleSpecifier(node.moduleSpecifier); + emitExternalModuleSpecifier(node); write(";"); writer.writeLine(); } - function emitExternalModuleSpecifier(moduleSpecifier) { - if (moduleSpecifier.kind === 9 /* StringLiteral */ && (!root) && (compilerOptions.out || compilerOptions.outFile)) { - var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, moduleSpecifier.parent); + function emitExternalModuleSpecifier(parent) { + var moduleSpecifier; + if (parent.kind === 223 /* ImportEqualsDeclaration */) { + var node = parent; + moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); + } + else { + var node = parent; + moduleSpecifier = node.moduleSpecifier; + } + if (moduleSpecifier.kind === 9 /* StringLiteral */ && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { + var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); if (moduleName) { write("\""); write(moduleName); @@ -29221,7 +30184,7 @@ var ts; } if (node.moduleSpecifier) { write(" from "); - emitExternalModuleSpecifier(node.moduleSpecifier); + emitExternalModuleSpecifier(node); } write(";"); writer.writeLine(); @@ -29236,7 +30199,7 @@ var ts; write("module "); } writeTextOfNode(currentText, node.name); - while (node.body.kind !== 219 /* ModuleBlock */) { + while (node.body.kind !== 221 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -29331,10 +30294,10 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; case 148 /* ConstructSignature */: @@ -29348,14 +30311,14 @@ var ts; if (node.parent.flags & 64 /* Static */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 216 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -29389,7 +30352,7 @@ var ts; function getHeritageClauseVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + if (node.parent.parent.kind === 216 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : @@ -29473,7 +30436,7 @@ var ts; function emitVariableDeclaration(node) { // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted // so there is no check needed to see if declaration is visible - if (node.kind !== 211 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + if (node.kind !== 213 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } @@ -29495,7 +30458,7 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 211 /* VariableDeclaration */) { + if (node.kind === 213 /* VariableDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29511,7 +30474,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 216 /* ClassDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29543,7 +30506,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 189 /* OmittedExpression */) { elements.push(element); } } @@ -29685,13 +30648,13 @@ var ts; // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 215 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } else if (node.kind === 143 /* MethodDeclaration */) { emitClassMemberDeclarationFlags(node); } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 215 /* FunctionDeclaration */) { write("function "); writeTextOfNode(currentText, node.name); } @@ -29712,6 +30675,8 @@ var ts; emitSignatureDeclaration(node); } function emitSignatureDeclaration(node) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; // Construct signature or constructor type write new Signature if (node.kind === 148 /* ConstructSignature */ || node.kind === 153 /* ConstructorType */) { write("new "); @@ -29723,8 +30688,6 @@ var ts; else { write("("); } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; // Parameters emitCommaList(node.parameters, emitParameterDeclaration); if (node.kind === 149 /* IndexSignature */) { @@ -29780,7 +30743,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 216 /* ClassDeclaration */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -29794,7 +30757,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -29872,7 +30835,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 216 /* ClassDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29885,7 +30848,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29897,12 +30860,12 @@ var ts; } function emitBindingPattern(bindingPattern) { // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 161 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 163 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 162 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 164 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -29913,15 +30876,7 @@ var ts; } } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.kind === 187 /* OmittedExpression */) { + if (bindingElement.kind === 189 /* OmittedExpression */) { // If bindingElement is an omittedExpression (i.e. containing elision), // we will emit blank space (although this may differ from users' original code, // it allows emitSeparatedList to write separator appropriately) @@ -29930,7 +30885,7 @@ var ts; // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 163 /* BindingElement */) { + else if (bindingElement.kind === 165 /* BindingElement */) { if (bindingElement.propertyName) { // bindingElement has propertyName property in the following case: // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" @@ -29969,20 +30924,20 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: - case 218 /* ModuleDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 215 /* InterfaceDeclaration */: - case 214 /* ClassDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: + case 215 /* FunctionDeclaration */: + case 220 /* ModuleDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 217 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 219 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: // Import declaration without import clause is visible, otherwise it is not visible return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return emitExportDeclaration(node); case 144 /* Constructor */: case 143 /* MethodDeclaration */: @@ -29998,35 +30953,57 @@ var ts; case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return emitPropertyDeclaration(node); - case 247 /* EnumMember */: + case 249 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return emitExportAssignment(node); - case 248 /* SourceFile */: + case 250 /* SourceFile */: return emitSourceFile(node); } } - function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 4096 /* DeclarationFile */ - ? referencedFile.fileName // Declaration file, use declaration file name - : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) - ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file - : ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; // Global out file - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ false); - referencePathsOutput += "/// " + newLine; + /** + * Adds the reference to referenced file, returns true if global file reference was emitted + * @param referencedFile + * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not + */ + function writeReferencePath(referencedFile, addBundledFileReference) { + var declFileName; + var addedBundledEmitReference = false; + if (ts.isDeclarationFile(referencedFile)) { + // Declaration file, use declaration file name + declFileName = referencedFile.fileName; + } + else { + // Get the declaration file path + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + } + if (declFileName) { + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + referencePathsOutput += "/// " + newLine; + } + return addedBundledEmitReference; + function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path + if (isBundledEmit && !addBundledFileReference) { + return; + } + ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); + declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; + addedBundledEmitReference = isBundledEmit; + } } } /* @internal */ - function writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); - // TODO(shkamat): Should we not write any declaration file if any of them can produce error, - // or should we just not write this file like we are doing now - if (!emitDeclarationResult.reportedDeclarationError) { + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; + if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); + ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM); } + return emitSkipped; function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { var appliedSyncOutputPos = 0; var declarationOutput = ""; @@ -30045,14 +31022,11 @@ var ts; ts.writeDeclarationFile = writeDeclarationFile; })(ts || (ts = {})); /// +/// /// /* @internal */ var ts; (function (ts) { - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); - } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; function getResolvedExternalModuleName(host, file) { return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); } @@ -30345,43 +31319,17 @@ var ts; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\n return new Promise(function (resolve, reject) {\n generator = generator.call(thisArg, _arguments);\n function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\n function onfulfill(value) { try { step(\"next\", value); } catch (e) { reject(e); } }\n function onreject(value) { try { step(\"throw\", value); } catch (e) { reject(e); } }\n function step(verb, value) {\n var result = generator[verb](value);\n result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\n }\n step(\"next\", void 0);\n });\n};"; var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || 0 /* ES3 */; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; - var diagnostics = []; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emitSkipped = false; var newLine = host.getNewLine(); - var jsxDesugaring = host.getCompilerOptions().jsx !== 1 /* Preserve */; - var shouldEmitJsx = function (s) { return (s.languageVariant === 1 /* JSX */ && !jsxDesugaring); }; - var outFile = compilerOptions.outFile || compilerOptions.out; var emitJavaScript = createFileEmitter(); - if (targetSourceFile === undefined) { - if (outFile) { - emitFile(outFile); - } - else { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - } - } - else { - // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service) - if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!ts.isDeclarationFile(targetSourceFile) && outFile) { - emitFile(outFile); - } - } - // Sort and make the unique list of diagnostics - diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { - emitSkipped: false, - diagnostics: diagnostics, + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), sourceMaps: sourceMapDataList }; function isUniqueLocalName(name, container) { @@ -30429,6 +31377,8 @@ var ts; function createFileEmitter() { var writer = ts.createTextWriter(newLine); var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); + var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; var currentSourceFile; var currentText; var currentLineMap; @@ -30451,40 +31401,18 @@ var ts; var decorateEmitted; var paramEmitted; var awaiterEmitted; - var tempFlags; + var tempFlags = 0; var tempVariables; var tempParameters; var externalImports; var exportSpecifiers; var exportEquals; - var hasExportStars; - /** Write emitted output to disk */ - var writeEmittedFiles = writeJavaScriptFile; + var hasExportStarsToExportValues; var detachedCommentsInfo; - var writeComment = ts.writeCommentRange; - /** Emit a node */ - var emit = emitNodeWithCommentsAndWithoutSourcemap; - /** Called just before starting emit of a node */ - var emitStart = function (node) { }; - /** Called once the emit of the node is done */ - var emitEnd = function (node) { }; - /** Emit the text for the given token that comes after startPos - * This by default writes the text provided with the given tokenKind - * but if optional emitFn callback is provided the text is emitted using the callback instead of default text - * @param tokenKind the kind of the token to search and emit - * @param startPos the position in the source to start searching for the token - * @param emitFn if given will be invoked to emit the text instead of actual token emit */ - var emitToken = emitTokenText; - /** Called to before starting the lexical scopes as in function/class in the emitted code because of node - * @param scopeDeclaration node that starts the lexical scope - * @param scopeName Optional name of this scope instead of deducing one from the declaration node */ - var scopeEmitStart = function (scopeDeclaration, scopeName) { }; - /** Called after coming out of the scope */ - var scopeEmitEnd = function () { }; /** Sourcemap data that will get encoded */ var sourceMapData; - /** The root file passed to the emit function (if present) */ - var root; + /** Is the file being emitted into its own file */ + var isOwnFileEmit; /** If removeComments is true, no leading-comments needed to be emitted **/ var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var moduleEmitDelegates = (_a = {}, @@ -30504,15 +31432,32 @@ var ts; _b ); return doEmit; - function doEmit(jsFilePath, rootFile) { + function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + generatedNameSet = {}; + nodeToGeneratedName = []; + isOwnFileEmit = !isBundledEmit; + // Emit helpers from all the files + if (isBundledEmit && modulekind) { + ts.forEach(sourceFiles, emitEmitHelpers); + } + // Do not call emit directly. It does not set the currentSourceFile. + ts.forEach(sourceFiles, emitSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# sourceMappingURL=" + sourceMappingURL); + } + writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM); // reset the state + sourceMap.reset(); writer.reset(); currentSourceFile = undefined; currentText = undefined; currentLineMap = undefined; exportFunctionForFile = undefined; - generatedNameSet = {}; - nodeToGeneratedName = []; + generatedNameSet = undefined; + nodeToGeneratedName = undefined; computedPropertyNamesToGeneratedNames = undefined; convertedLoopState = undefined; extendsEmitted = false; @@ -30525,32 +31470,12 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = undefined; + hasExportStarsToExportValues = undefined; detachedCommentsInfo = undefined; sourceMapData = undefined; isEs6Module = false; renamedDependencies = undefined; isCurrentFileExternalModule = false; - root = rootFile; - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - initializeEmitterWithSourceMaps(jsFilePath, root); - } - if (root) { - // Do not call emit directly. It does not set the currentSourceFile. - emitSourceFile(root); - } - else { - if (modulekind) { - ts.forEach(host.getSourceFiles(), emitEmitHelpers); - } - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if ((!isExternalModuleOrDeclarationFile(sourceFile)) || (modulekind && ts.isExternalModule(sourceFile))) { - emitSourceFile(sourceFile); - } - }); - } - writeLine(); - writeEmittedFiles(writer.getText(), jsFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM); } function emitSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -30561,7 +31486,8 @@ var ts; renamedDependencies = sourceFile.renamedDependencies; currentFileIdentifiers = sourceFile.identifiers; isCurrentFileExternalModule = ts.isExternalModule(sourceFile); - emit(sourceFile); + setSourceFile(sourceFile); + emitNodeWithCommentsAndWithoutSourcemap(sourceFile); } function isUniqueName(name) { return !resolver.hasGlobalName(name) && @@ -30630,17 +31556,17 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return makeUniqueName(node.text); - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: + case 220 /* ModuleDeclaration */: + case 219 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 222 /* ImportDeclaration */: - case 228 /* ExportDeclaration */: + case 224 /* ImportDeclaration */: + case 230 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 213 /* FunctionDeclaration */: - case 214 /* ClassDeclaration */: - case 227 /* ExportAssignment */: + case 215 /* FunctionDeclaration */: + case 216 /* ClassDeclaration */: + case 229 /* ExportAssignment */: return generateNameForExportDefault(); - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: return generateNameForClassExpression(); } } @@ -30648,338 +31574,15 @@ var ts; var id = ts.getNodeId(node); return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); } - function initializeEmitterWithSourceMaps(jsFilePath, root) { - var sourceMapDir; // The directory in which sourcemap will be - // Current source map file and its index in the sources list - var sourceMapSourceIndex = -1; - // Names and its index map - var sourceMapNameIndexMap = {}; - var sourceMapNameIndices = []; - function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; + /** Write emitted output to disk */ + function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark) { + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false); } - // Last recorded and encoded spans - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - var lastEncodedNameIndex = 0; - // Encoding for sourcemap span - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - // Line/Comma delimiters - if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { - // Emit comma to separate the entry - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - // Emit line delimiters - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - // 1. Relative Column 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - // 2. Relative sourceIndex - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - // 3. Relative sourceLine 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - // 4. Relative sourceColumn 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - // 5. Relative namePosition 0 based - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - function base64VLQFormatEncode(inValue) { - function base64FormatEncode(inValue) { - if (inValue < 64) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - // Add a new least significant bit that has the sign of the value. - // if negative number the least significant bit that gets added to the number has value 1 - // else least significant bit value that gets added is 0 - // eg. -1 changes to binary : 01 [1] => 3 - // +1 changes to binary : 01 [0] => 2 - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - // Encode 5 bits at a time starting from least significant bits - var encodedStr = ""; - do { - var currentDigit = inValue & 31; // 11111 - inValue = inValue >> 5; - if (inValue > 0) { - // There are still more digits to decode, set the msb (6th bit) - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; - } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); } - function recordSourceMapSpan(pos) { - var sourceLinePos = ts.computeLineAndCharacterOfPosition(currentLineMap, pos); - // Convert the location to be one-based. - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); - // If this location wasn't recorded or the location in source is going backwards, record the span - if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine !== emittedLine || - lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || - (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && - (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || - (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - // Encode the last recordedSpan before assigning new - encodeLastRecordedSourceMapSpan(); - // New span - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - nameIndex: getSourceMapNameIndex(), - sourceIndex: sourceMapSourceIndex - }; - } - else { - // Take the new pos instead since there is no change in emittedLine and column since last location - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - } - function recordEmitNodeStartSpan(node) { - // Get the token pos after skipping to the token (ignoring the leading trivia) - recordSourceMapSpan(ts.skipTrivia(currentText, node.pos)); - } - function recordEmitNodeEndSpan(node) { - recordSourceMapSpan(node.end); - } - function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentText, startPos); - recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); - recordSourceMapSpan(tokenEndPos); - return tokenEndPos; - } - function recordNewSourceFileStart(node) { - // Add the file to tsFilePaths - // If sourceroot option: Use the relative path corresponding to the common directory path - // otherwise source locations relative to map file location - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true)); - sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; - // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(node.fileName); - if (compilerOptions.inlineSources) { - if (!sourceMapData.sourceMapSourcesContent) { - sourceMapData.sourceMapSourcesContent = []; - } - sourceMapData.sourceMapSourcesContent.push(node.text); - } - } - function recordScopeNameOfNode(node, scopeName) { - function recordScopeNameIndex(scopeNameIndex) { - sourceMapNameIndices.push(scopeNameIndex); - } - function recordScopeNameStart(scopeName) { - var scopeNameIndex = -1; - if (scopeName) { - var parentIndex = getSourceMapNameIndex(); - if (parentIndex !== -1) { - // Child scopes are always shown with a dot (even if they have no name), - // unless it is a computed property. Then it is shown with brackets, - // but the brackets are included in the name. - var name_21 = node.name; - if (!name_21 || name_21.kind !== 136 /* ComputedPropertyName */) { - scopeName = "." + scopeName; - } - scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; - } - scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); - if (scopeNameIndex === undefined) { - scopeNameIndex = sourceMapData.sourceMapNames.length; - sourceMapData.sourceMapNames.push(scopeName); - sourceMapNameIndexMap[scopeName] = scopeNameIndex; - } - } - recordScopeNameIndex(scopeNameIndex); - } - if (scopeName) { - // The scope was already given a name use it - recordScopeNameStart(scopeName); - } - else if (node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */ || - node.kind === 143 /* MethodDeclaration */ || - node.kind === 142 /* MethodSignature */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */ || - node.kind === 218 /* ModuleDeclaration */ || - node.kind === 214 /* ClassDeclaration */ || - node.kind === 217 /* EnumDeclaration */) { - // Declaration and has associated name use it - if (node.name) { - var name_22 = node.name; - // For computed property names, the text will include the brackets - scopeName = name_22.kind === 136 /* ComputedPropertyName */ - ? ts.getTextOfNode(name_22) - : node.name.text; - } - recordScopeNameStart(scopeName); - } - else { - // Block just use the name from upper level scope - recordScopeNameIndex(getSourceMapNameIndex()); - } - } - function recordScopeNameEnd() { - sourceMapNameIndices.pop(); - } - ; - function writeCommentRangeWithMap(currentText, currentLineMap, writer, comment, newLine) { - recordSourceMapSpan(comment.pos); - ts.writeCommentRange(currentText, currentLineMap, writer, comment, newLine); - recordSourceMapSpan(comment.end); - } - function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) { - if (typeof JSON !== "undefined") { - var map_1 = { - version: version, - file: file, - sourceRoot: sourceRoot, - sources: sources, - names: names, - mappings: mappings - }; - if (sourcesContent !== undefined) { - map_1.sourcesContent = sourcesContent; - } - return JSON.stringify(map_1); - } - return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\" " + (sourcesContent !== undefined ? ",\"sourcesContent\":[" + serializeStringArray(sourcesContent) + "]" : "") + "}"; - function serializeStringArray(list) { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { - if (i) { - output += ","; - } - output += "\"" + ts.escapeString(list[i]) + "\""; - } - return output; - } - } - function writeJavaScriptAndSourceMapFile(emitOutput, jsFilePath, writeByteOrderMark) { - encodeLastRecordedSourceMapSpan(); - var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent); - sourceMapDataList.push(sourceMapData); - var sourceMapUrl; - if (compilerOptions.inlineSourceMap) { - // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.convertToBase64(sourceMapText); - sourceMapUrl = "//# sourceMappingURL=data:application/json;base64," + base64SourceMapText; - } - else { - // Write source map file - ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, /*writeByteOrderMark*/ false); - sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL; - } - // Write sourcemap url to the js file and write the js file - writeJavaScriptFile(emitOutput + sourceMapUrl, jsFilePath, writeByteOrderMark); - } - // Initialize source map data - var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)); - sourceMapData = { - sourceMapFilePath: jsFilePath + ".map", - jsSourceMappingURL: sourceMapJsFile + ".map", - sourceMapFile: sourceMapJsFile, - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapSourcesContent: undefined, - sourceMapDecodedMappings: [] - }; - // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the - // relative paths of the sources list in the sourcemap - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (root) { - // For modules or multiple emit files the mapRoot will have directory structure like the sources - // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - // The relative paths are relative to the common directory - sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), // get the relative sourceMapDir path based on jsFilePath - ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap - host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); - } - function emitNodeWithSourceMap(node) { - if (node) { - if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node); - } - if (node.kind !== 248 /* SourceFile */) { - recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node); - recordEmitNodeEndSpan(node); - } - else { - recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node); - } - } - } - function emitNodeWithCommentsAndWithSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - writeEmittedFiles = writeJavaScriptAndSourceMapFile; - emit = emitNodeWithCommentsAndWithSourcemap; - emitStart = recordEmitNodeStartSpan; - emitEnd = recordEmitNodeEndSpan; - emitToken = writeTextWithSpanRecord; - scopeEmitStart = recordScopeNameOfNode; - scopeEmitEnd = recordScopeNameEnd; - writeComment = writeCommentRangeWithMap; - } - function writeJavaScriptFile(emitOutput, jsFilePath, writeByteOrderMark) { - ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark); } // Create a temporary variable with a unique unused name. function createTempVariable(flags) { @@ -31011,7 +31614,15 @@ var ts; write(";"); } } - function emitTokenText(tokenKind, startPos, emitFn) { + /** Emit the text for the given token that comes after startPos + * This by default writes the text provided with the given tokenKind + * but if optional emitFn callback is provided the text is emitted using the callback instead of default text + * @param tokenKind the kind of the token to search and emit + * @param startPos the position in the source to start searching for the token + * @param emitFn if given will be invoked to emit the text instead of actual token emit */ + function emitToken(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentText, startPos); + emitPos(tokenStartPos); var tokenString = ts.tokenToString(tokenKind); if (emitFn) { emitFn(); @@ -31019,7 +31630,9 @@ var ts; else { write(tokenString); } - return startPos + tokenString.length; + var tokenEndPos = tokenStartPos + tokenString.length; + emitPos(tokenEndPos); + return tokenEndPos; } function emitOptional(prefix, node) { if (node) { @@ -31036,11 +31649,6 @@ var ts; write(")"); } } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { ts.Debug.assert(nodes.length > 0); increaseIndent(); @@ -31113,7 +31721,7 @@ var ts; } function emitCommaList(nodes) { if (nodes) { - emitList(nodes, 0, nodes.length, /*multiline*/ false, /*trailingComma*/ false); + emitList(nodes, 0, nodes.length, /*multiLine*/ false, /*trailingComma*/ false); } } function emitLines(nodes) { @@ -31228,10 +31836,10 @@ var ts; write("("); emit(tempVariable); // Now we emit the expressions - if (node.template.kind === 183 /* TemplateExpression */) { + if (node.template.kind === 185 /* TemplateExpression */) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 181 /* BinaryExpression */ + var needsParens = templateSpan.expression.kind === 183 /* BinaryExpression */ && templateSpan.expression.operatorToken.kind === 24 /* CommaToken */; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -31266,7 +31874,7 @@ var ts; // ("abc" + 1) << (2 + "") // rather than // "abc" + (1 << 2) + "" - var needsParens = templateSpan.expression.kind !== 172 /* ParenthesizedExpression */ + var needsParens = templateSpan.expression.kind !== 174 /* ParenthesizedExpression */ && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; if (i > 0 || headEmitted) { // If this is the first span and the head was not emitted, then this templateSpan's @@ -31308,11 +31916,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: return parent.expression === template; - case 170 /* TaggedTemplateExpression */: - case 172 /* ParenthesizedExpression */: + case 172 /* TaggedTemplateExpression */: + case 174 /* ParenthesizedExpression */: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; @@ -31333,7 +31941,7 @@ var ts; // TODO (drosen): Note that we need to account for the upcoming 'yield' and // spread ('...') unary operators that are anticipated for ES6. switch (expression.kind) { - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: switch (expression.operatorToken.kind) { case 37 /* AsteriskToken */: case 39 /* SlashToken */: @@ -31345,8 +31953,8 @@ var ts; default: return -1 /* LessThan */; } - case 184 /* YieldExpression */: - case 182 /* ConditionalExpression */: + case 186 /* YieldExpression */: + case 184 /* ConditionalExpression */: return -1 /* LessThan */; default: return 1 /* GreaterThan */; @@ -31374,13 +31982,13 @@ var ts; /// these emit into an object literal property name, we don't need to be worried /// about keywords, just non-identifier characters function emitAttributeName(name) { - if (/[A-Za-z_]+[\w*]/.test(name.text)) { - write("\""); + if (/^[A-Za-z_]\w*$/.test(name.text)) { emit(name); - write("\""); } else { + write("\""); emit(name); + write("\""); } } /// Emit an name/value pair for an attribute (e.g. "x: 3") @@ -31396,7 +32004,7 @@ var ts; } function emitJsxElement(openingNode, children) { var syntheticReactRef = ts.createSynthesizedNode(69 /* Identifier */); - syntheticReactRef.text = "React"; + syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; syntheticReactRef.parent = openingNode; // Call React.createElement(tag, ... emitLeadingComments(openingNode); @@ -31413,12 +32021,12 @@ var ts; // Either emit one big object literal (no spread attribs), or // a call to React.__spread var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 239 /* JsxSpreadAttribute */; })) { + if (ts.forEach(attrs, function (attr) { return attr.kind === 241 /* JsxSpreadAttribute */; })) { emitExpressionIdentifier(syntheticReactRef); write(".__spread("); var haveOpenedObjectLiteral = false; for (var i_1 = 0; i_1 < attrs.length; i_1++) { - if (attrs[i_1].kind === 239 /* JsxSpreadAttribute */) { + if (attrs[i_1].kind === 241 /* JsxSpreadAttribute */) { // If this is the first argument, we need to emit a {} as the first argument if (i_1 === 0) { write("{}, "); @@ -31433,7 +32041,7 @@ var ts; emit(attrs[i_1].expression); } else { - ts.Debug.assert(attrs[i_1].kind === 238 /* JsxAttribute */); + ts.Debug.assert(attrs[i_1].kind === 240 /* JsxAttribute */); if (haveOpenedObjectLiteral) { write(", "); } @@ -31467,11 +32075,11 @@ var ts; if (children) { for (var i = 0; i < children.length; i++) { // Don't emit empty expressions - if (children[i].kind === 240 /* JsxExpression */ && !(children[i].expression)) { + if (children[i].kind === 242 /* JsxExpression */ && !(children[i].expression)) { continue; } // Don't emit empty strings - if (children[i].kind === 236 /* JsxText */) { + if (children[i].kind === 238 /* JsxText */) { var text = getTextToEmit(children[i]); if (text !== undefined) { write(", \""); @@ -31489,11 +32097,11 @@ var ts; write(")"); // closes "React.createElement(" emitTrailingComments(openingNode); } - if (node.kind === 233 /* JsxElement */) { + if (node.kind === 235 /* JsxElement */) { emitJsxElement(node.openingElement, node.children); } else { - ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(node.kind === 236 /* JsxSelfClosingElement */); emitJsxElement(node); } } @@ -31515,11 +32123,11 @@ var ts; if (i > 0) { write(" "); } - if (attribs[i].kind === 239 /* JsxSpreadAttribute */) { + if (attribs[i].kind === 241 /* JsxSpreadAttribute */) { emitJsxSpreadAttribute(attribs[i]); } else { - ts.Debug.assert(attribs[i].kind === 238 /* JsxAttribute */); + ts.Debug.assert(attribs[i].kind === 240 /* JsxAttribute */); emitJsxAttribute(attribs[i]); } } @@ -31527,11 +32135,11 @@ var ts; function emitJsxOpeningOrSelfClosingElement(node) { write("<"); emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 234 /* JsxSelfClosingElement */)) { + if (node.attributes.length > 0 || (node.kind === 236 /* JsxSelfClosingElement */)) { write(" "); } emitAttributes(node.attributes); - if (node.kind === 234 /* JsxSelfClosingElement */) { + if (node.kind === 236 /* JsxSelfClosingElement */) { write("/>"); } else { @@ -31550,11 +32158,11 @@ var ts; } emitJsxClosingElement(node.closingElement); } - if (node.kind === 233 /* JsxElement */) { + if (node.kind === 235 /* JsxElement */) { emitJsxElement(node); } else { - ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(node.kind === 236 /* JsxSelfClosingElement */); emitJsxOpeningOrSelfClosingElement(node); } } @@ -31562,7 +32170,7 @@ var ts; // In a sense, it does not actually emit identifiers as much as it declares a name for a specific property. // For example, this is utilized when feeding in a result to Object.defineProperty. function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 163 /* BindingElement */); + ts.Debug.assert(node.kind !== 165 /* BindingElement */); if (node.kind === 9 /* StringLiteral */) { emitLiteral(node); } @@ -31610,59 +32218,60 @@ var ts; function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 164 /* ArrayLiteralExpression */: - case 189 /* AsExpression */: - case 181 /* BinaryExpression */: - case 168 /* CallExpression */: - case 241 /* CaseClause */: + case 166 /* ArrayLiteralExpression */: + case 191 /* AsExpression */: + case 183 /* BinaryExpression */: + case 170 /* CallExpression */: + case 243 /* CaseClause */: case 136 /* ComputedPropertyName */: - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: case 139 /* Decorator */: - case 175 /* DeleteExpression */: - case 197 /* DoStatement */: - case 167 /* ElementAccessExpression */: - case 227 /* ExportAssignment */: - case 195 /* ExpressionStatement */: - case 188 /* ExpressionWithTypeArguments */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 196 /* IfStatement */: - case 234 /* JsxSelfClosingElement */: - case 235 /* JsxOpeningElement */: - case 239 /* JsxSpreadAttribute */: - case 240 /* JsxExpression */: - case 169 /* NewExpression */: - case 172 /* ParenthesizedExpression */: - case 180 /* PostfixUnaryExpression */: - case 179 /* PrefixUnaryExpression */: - case 204 /* ReturnStatement */: - case 246 /* ShorthandPropertyAssignment */: - case 185 /* SpreadElementExpression */: - case 206 /* SwitchStatement */: - case 170 /* TaggedTemplateExpression */: - case 190 /* TemplateSpan */: - case 208 /* ThrowStatement */: - case 171 /* TypeAssertionExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 184 /* YieldExpression */: + case 177 /* DeleteExpression */: + case 199 /* DoStatement */: + case 169 /* ElementAccessExpression */: + case 229 /* ExportAssignment */: + case 197 /* ExpressionStatement */: + case 190 /* ExpressionWithTypeArguments */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 198 /* IfStatement */: + case 239 /* JsxClosingElement */: + case 236 /* JsxSelfClosingElement */: + case 237 /* JsxOpeningElement */: + case 241 /* JsxSpreadAttribute */: + case 242 /* JsxExpression */: + case 171 /* NewExpression */: + case 174 /* ParenthesizedExpression */: + case 182 /* PostfixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: + case 206 /* ReturnStatement */: + case 248 /* ShorthandPropertyAssignment */: + case 187 /* SpreadElementExpression */: + case 208 /* SwitchStatement */: + case 172 /* TaggedTemplateExpression */: + case 192 /* TemplateSpan */: + case 210 /* ThrowStatement */: + case 173 /* TypeAssertionExpression */: + case 178 /* TypeOfExpression */: + case 179 /* VoidExpression */: + case 200 /* WhileStatement */: + case 207 /* WithStatement */: + case 186 /* YieldExpression */: return true; - case 163 /* BindingElement */: - case 247 /* EnumMember */: + case 165 /* BindingElement */: + case 249 /* EnumMember */: case 138 /* Parameter */: - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: case 141 /* PropertyDeclaration */: - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: return parent.initializer === node; - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: return parent.expression === node; - case 174 /* ArrowFunction */: - case 173 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 175 /* FunctionExpression */: return parent.body === node; - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return parent.moduleReference === node; case 135 /* QualifiedName */: return parent.left === node; @@ -31676,7 +32285,7 @@ var ts; } var container = resolver.getReferencedExportContainer(node); if (container) { - if (container.kind === 248 /* SourceFile */) { + if (container.kind === 250 /* SourceFile */) { // Identifier references module export if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) { write("exports."); @@ -31692,17 +32301,17 @@ var ts; if (modulekind !== 5 /* ES6 */) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { - if (declaration.kind === 223 /* ImportClause */) { + if (declaration.kind === 225 /* ImportClause */) { // Identifier references default import write(getGeneratedNameForNode(declaration.parent)); write(languageVersion === 0 /* ES3 */ ? "[\"default\"]" : ".default"); return; } - else if (declaration.kind === 226 /* ImportSpecifier */) { + else if (declaration.kind === 228 /* ImportSpecifier */) { // Identifier references named import write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_23 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_23); + var name_21 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_21); if (languageVersion === 0 /* ES3 */ && identifier === "default") { write("[\"default\"]"); } @@ -31733,10 +32342,10 @@ var ts; if (languageVersion < 2 /* ES6 */) { var parent_6 = node.parent; switch (parent_6.kind) { - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 211 /* VariableDeclaration */: + case 165 /* BindingElement */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 213 /* VariableDeclaration */: return parent_6.name === node && resolver.isNestedRedeclaration(parent_6); } } @@ -31746,8 +32355,8 @@ var ts; if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { // in converted loop body arguments cannot be used directly. - var name_24 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_24); + var name_22 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_22); return; } } @@ -31771,6 +32380,9 @@ var ts; if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { write("_this"); } + else if (convertedLoopState) { + write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); + } else { write("this"); } @@ -31844,10 +32456,10 @@ var ts; } } function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 181 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { + if (node.parent.kind === 183 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { return true; } - else if (node.parent.kind === 182 /* ConditionalExpression */ && node.parent.condition === node) { + else if (node.parent.kind === 184 /* ConditionalExpression */ && node.parent.condition === node) { return true; } return false; @@ -31855,11 +32467,11 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 69 /* Identifier */: - case 164 /* ArrayLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 172 /* ParenthesizedExpression */: + case 166 /* ArrayLiteralExpression */: + case 168 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: + case 170 /* CallExpression */: + case 174 /* ParenthesizedExpression */: // This list is not exhaustive and only includes those cases that are relevant // to the check in emitArrayLiteral. More cases can be added as needed. return false; @@ -31879,17 +32491,17 @@ var ts; write(", "); } var e = elements[pos]; - if (e.kind === 185 /* SpreadElementExpression */) { + if (e.kind === 187 /* SpreadElementExpression */) { e = e.expression; emitParenthesizedIf(e, /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164 /* ArrayLiteralExpression */) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 166 /* ArrayLiteralExpression */) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 185 /* SpreadElementExpression */) { + while (i < length && elements[i].kind !== 187 /* SpreadElementExpression */) { i++; } write("["); @@ -31912,7 +32524,7 @@ var ts; } } function isSpreadElementExpression(node) { - return node.kind === 185 /* SpreadElementExpression */; + return node.kind === 187 /* SpreadElementExpression */; } function emitArrayLiteral(node) { var elements = node.elements; @@ -31921,7 +32533,7 @@ var ts; } else if (languageVersion >= 2 /* ES6 */ || !ts.forEach(elements, isSpreadElementExpression)) { write("["); - emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces:*/ false); + emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces*/ false); write("]"); } else { @@ -31941,7 +32553,7 @@ var ts; // then try to preserve the original shape of the object literal. // Otherwise just try to preserve the formatting. if (numElements === properties.length) { - emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= 1 /* ES5 */, /* spacesBetweenBraces */ true); + emitLinePreservingList(node, properties, /*allowTrailingComma*/ languageVersion >= 1 /* ES5 */, /*spacesBetweenBraces*/ true); } else { var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; @@ -32034,10 +32646,10 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 245 /* PropertyAssignment */) { + if (property.kind === 247 /* PropertyAssignment */) { emit(property.initializer); } - else if (property.kind === 246 /* ShorthandPropertyAssignment */) { + else if (property.kind === 248 /* ShorthandPropertyAssignment */) { emitExpressionIdentifier(property.name); } else if (property.kind === 143 /* MethodDeclaration */) { @@ -32090,21 +32702,21 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(181 /* BinaryExpression */, startsOnNewLine); + var result = ts.createSynthesizedNode(183 /* BinaryExpression */, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(166 /* PropertyAccessExpression */); + var result = ts.createSynthesizedNode(168 /* PropertyAccessExpression */); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(21 /* DotToken */); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(167 /* ElementAccessExpression */); + var result = ts.createSynthesizedNode(169 /* ElementAccessExpression */); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; @@ -32112,7 +32724,7 @@ var ts; function parenthesizeForAccess(expr) { // When diagnosing whether the expression needs parentheses, the decision should be based // on the innermost expression in a chain of nested type assertions. - while (expr.kind === 171 /* TypeAssertionExpression */ || expr.kind === 189 /* AsExpression */) { + while (expr.kind === 173 /* TypeAssertionExpression */ || expr.kind === 191 /* AsExpression */) { expr = expr.expression; } // isLeftHandSideExpression is almost the correct criterion for when it is not necessary @@ -32124,11 +32736,11 @@ var ts; // 1.x -> not the same as (1).x // if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 169 /* NewExpression */ && + expr.kind !== 171 /* NewExpression */ && expr.kind !== 8 /* NumericLiteral */) { return expr; } - var node = ts.createSynthesizedNode(172 /* ParenthesizedExpression */); + var node = ts.createSynthesizedNode(174 /* ParenthesizedExpression */); node.expression = expr; return node; } @@ -32163,7 +32775,7 @@ var ts; // Return true if identifier resolves to an exported member of a namespace function isNamespaceExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 248 /* SourceFile */; + return container && container.kind !== 250 /* SourceFile */; } function emitShorthandPropertyAssignment(node) { // The name property of a short-hand property assignment is considered an expression position, so here @@ -32193,7 +32805,7 @@ var ts; if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 166 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 168 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -32204,7 +32816,7 @@ var ts; if (compilerOptions.isolatedModules) { return undefined; } - return node.kind === 166 /* PropertyAccessExpression */ || node.kind === 167 /* ElementAccessExpression */ + return node.kind === 168 /* PropertyAccessExpression */ || node.kind === 169 /* ElementAccessExpression */ ? resolver.getConstantValue(node) : undefined; } @@ -32296,6 +32908,9 @@ var ts; case 135 /* QualifiedName */: emitQualifiedNameAsExpression(node, useFallback); break; + default: + emitNodeWithoutSourceMap(node); + break; } } function emitIndexedAccess(node) { @@ -32308,10 +32923,10 @@ var ts; write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 185 /* SpreadElementExpression */; }); + return ts.forEach(elements, function (e) { return e.kind === 187 /* SpreadElementExpression */; }); } function skipParentheses(node) { - while (node.kind === 172 /* ParenthesizedExpression */ || node.kind === 171 /* TypeAssertionExpression */ || node.kind === 189 /* AsExpression */) { + while (node.kind === 174 /* ParenthesizedExpression */ || node.kind === 173 /* TypeAssertionExpression */ || node.kind === 191 /* AsExpression */) { node = node.expression; } return node; @@ -32332,13 +32947,13 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 166 /* PropertyAccessExpression */) { + if (expr.kind === 168 /* PropertyAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 167 /* ElementAccessExpression */) { + else if (expr.kind === 169 /* ElementAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("["); @@ -32383,7 +32998,7 @@ var ts; } else { emit(node.expression); - superCall = node.expression.kind === 166 /* PropertyAccessExpression */ && node.expression.expression.kind === 95 /* SuperKeyword */; + superCall = node.expression.kind === 168 /* PropertyAccessExpression */ && node.expression.expression.kind === 95 /* SuperKeyword */; } if (superCall && languageVersion < 2 /* ES6 */) { write(".call("); @@ -32425,7 +33040,7 @@ var ts; write(".bind.apply("); emit(target); write(", [void 0].concat("); - emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiline*/ false, /*trailingComma*/ false, /*useConcat*/ false); + emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ false); write(")))"); write("()"); } @@ -32452,12 +33067,12 @@ var ts; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. - if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 174 /* ArrowFunction */) { - if (node.expression.kind === 171 /* TypeAssertionExpression */ || node.expression.kind === 189 /* AsExpression */) { + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 176 /* ArrowFunction */) { + if (node.expression.kind === 173 /* TypeAssertionExpression */ || node.expression.kind === 191 /* AsExpression */) { var operand = node.expression.expression; // Make sure we consider all nested cast expressions, e.g.: // (-A).x; - while (operand.kind === 171 /* TypeAssertionExpression */ || operand.kind === 189 /* AsExpression */) { + while (operand.kind === 173 /* TypeAssertionExpression */ || operand.kind === 191 /* AsExpression */) { operand = operand.expression; } // We have an expression of the form: (SubExpr) @@ -32468,15 +33083,15 @@ var ts; // (typeof A).toString() should be emitted as (typeof A).toString() and not typeof A.toString() // new (A()) should be emitted as new (A()) and not new A() // (function foo() { })() should be emitted as an IIF (function foo(){})() and not declaration function foo(){} () - if (operand.kind !== 179 /* PrefixUnaryExpression */ && - operand.kind !== 177 /* VoidExpression */ && - operand.kind !== 176 /* TypeOfExpression */ && - operand.kind !== 175 /* DeleteExpression */ && - operand.kind !== 180 /* PostfixUnaryExpression */ && - operand.kind !== 169 /* NewExpression */ && - !(operand.kind === 168 /* CallExpression */ && node.parent.kind === 169 /* NewExpression */) && - !(operand.kind === 173 /* FunctionExpression */ && node.parent.kind === 168 /* CallExpression */) && - !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 166 /* PropertyAccessExpression */)) { + if (operand.kind !== 181 /* PrefixUnaryExpression */ && + operand.kind !== 179 /* VoidExpression */ && + operand.kind !== 178 /* TypeOfExpression */ && + operand.kind !== 177 /* DeleteExpression */ && + operand.kind !== 182 /* PostfixUnaryExpression */ && + operand.kind !== 171 /* NewExpression */ && + !(operand.kind === 170 /* CallExpression */ && node.parent.kind === 171 /* NewExpression */) && + !(operand.kind === 175 /* FunctionExpression */ && node.parent.kind === 170 /* CallExpression */) && + !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 168 /* PropertyAccessExpression */)) { emit(operand); return; } @@ -32505,14 +33120,15 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 211 /* VariableDeclaration */ || node.parent.kind === 163 /* BindingElement */); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 213 /* VariableDeclaration */ || node.parent.kind === 165 /* BindingElement */); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, /*isExported*/ true); } function emitPrefixUnaryExpression(node) { - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); + var exportChanged = (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) && + isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); if (exportChanged) { // emit // ++x @@ -32535,7 +33151,7 @@ var ts; // the resulting expression a prefix increment operation. And in the second, it will make the resulting // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. - if (node.operand.kind === 179 /* PrefixUnaryExpression */) { + if (node.operand.kind === 181 /* PrefixUnaryExpression */) { var operand = node.operand; if (node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) { write(" "); @@ -32591,10 +33207,10 @@ var ts; } var current = node; while (current) { - if (current.kind === 248 /* SourceFile */) { + if (current.kind === 250 /* SourceFile */) { return !isExported || ((ts.getCombinedNodeFlags(node) & 2 /* Export */) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 219 /* ModuleBlock */) { + else if (ts.isFunctionLike(current) || current.kind === 221 /* ModuleBlock */) { return false; } else { @@ -32614,8 +33230,8 @@ var ts; if (ts.isElementAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(167 /* ElementAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false); + synthesizedLHS = ts.createSynthesizedNode(169 /* ElementAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; if (leftHandSideExpression.argumentExpression.kind !== 8 /* NumericLiteral */ && leftHandSideExpression.argumentExpression.kind !== 9 /* StringLiteral */) { @@ -32631,8 +33247,8 @@ var ts; else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(166 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false); + synthesizedLHS = ts.createSynthesizedNode(168 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; @@ -32659,8 +33275,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 56 /* EqualsToken */ && - (node.left.kind === 165 /* ObjectLiteralExpression */ || node.left.kind === 164 /* ArrayLiteralExpression */)) { - emitDestructuring(node, node.parent.kind === 195 /* ExpressionStatement */); + (node.left.kind === 167 /* ObjectLiteralExpression */ || node.left.kind === 166 /* ArrayLiteralExpression */)) { + emitDestructuring(node, node.parent.kind === 197 /* ExpressionStatement */); } else { var exportChanged = node.operatorToken.kind >= 56 /* FirstAssignment */ && @@ -32725,7 +33341,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 192 /* Block */) { + if (node && node.kind === 194 /* Block */) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -32739,22 +33355,20 @@ var ts; } emitToken(15 /* OpenBraceToken */, node.pos); increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 219 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 218 /* ModuleDeclaration */); + if (node.kind === 221 /* ModuleBlock */) { + ts.Debug.assert(node.parent.kind === 220 /* ModuleDeclaration */); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 219 /* ModuleBlock */) { + if (node.kind === 221 /* ModuleBlock */) { emitTempDeclarations(/*newLine*/ true); } decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.statements.end); - scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 192 /* Block */) { + if (node.kind === 194 /* Block */) { write(" "); emit(node); } @@ -32766,7 +33380,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 174 /* ArrowFunction */); + emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 176 /* ArrowFunction */); write(";"); } function emitIfStatement(node) { @@ -32779,7 +33393,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(80 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 196 /* IfStatement */) { + if (node.elseStatement.kind === 198 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -32794,12 +33408,12 @@ var ts; function emitDoStatementWorker(node, loop) { write("do"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } - if (node.statement.kind === 192 /* Block */) { + if (node.statement.kind === 194 /* Block */) { write(" "); } else { @@ -32817,10 +33431,10 @@ var ts; emit(node.expression); write(")"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } /** @@ -32834,7 +33448,7 @@ var ts; return false; } if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 24576 /* BlockScoped */) === 0) { - // we are inside a converted loop - this can only happen in downlevel scenarios + // we are inside a converted loop - this can only happen in downlevel scenarios // record names for all variable declarations for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { var varDecl = _b[_a]; @@ -32898,7 +33512,7 @@ var ts; } else { var loop = convertLoopBody(node); - if (node.parent.kind === 207 /* LabeledStatement */) { + if (node.parent.kind === 209 /* LabeledStatement */) { // if parent of the loop was labeled statement - attach the label to loop skipping converted loop body emitLabelAndColon(node.parent); } @@ -32909,10 +33523,10 @@ var ts; var functionName = makeUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + if (node.initializer.kind === 214 /* VariableDeclarationList */) { loopInitializer = node.initializer; } break; @@ -32926,7 +33540,7 @@ var ts; collectNames(varDeclaration.name); } } - var bodyIsBlock = node.statement.kind === 192 /* Block */; + var bodyIsBlock = node.statement.kind === 194 /* Block */; var paramList = loopParameters ? loopParameters.join(", ") : ""; writeLine(); write("var " + functionName + " = function(" + paramList + ")"); @@ -32945,6 +33559,11 @@ var ts; // use the same name in all nested loops convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; } + if (convertedOuterLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.thisName = convertedOuterLoopState.thisName; + } if (convertedOuterLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop @@ -32971,6 +33590,21 @@ var ts; writeLine(); } } + if (convertedLoopState.thisName) { + // if alias for this is set + if (convertedOuterLoopState) { + // pass it to outer converted loop + convertedOuterLoopState.thisName = convertedLoopState.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + write("var " + convertedLoopState.thisName + " = this;"); + writeLine(); + } + } if (convertedLoopState.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later if (convertedOuterLoopState) { @@ -33027,7 +33661,7 @@ var ts; if (emitAsEmbeddedStatement) { emitEmbeddedStatement(node.statement); } - else if (node.statement.kind === 192 /* Block */) { + else if (node.statement.kind === 194 /* Block */) { emitLines(node.statement.statements); } else { @@ -33097,8 +33731,8 @@ var ts; } write("switch(" + loopResultVariable + ") {"); increaseIndent(); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /* isBreak */ true, loopResultVariable, outerLoop); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /* isBreak */ false, loopResultVariable, outerLoop); + emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /*isBreak*/ true, loopResultVariable, outerLoop); + emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /*isBreak*/ false, loopResultVariable, outerLoop); decreaseIndent(); writeLine(); write("}"); @@ -33113,7 +33747,7 @@ var ts; write("case \"" + labelMarker + "\": "); // if there are no outer converted loop or outer label in question is located inside outer converted loop // then emit labeled break\continue - // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { if (isBreak) { write("break "); @@ -33137,7 +33771,7 @@ var ts; var endPos = emitToken(86 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 214 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); if (startIsEmitted) { @@ -33156,14 +33790,14 @@ var ts; emitOptional(" ", node.incrementor); write(")"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 /* ES6 */ && node.kind === 201 /* ForOfStatement */) { + if (languageVersion < 2 /* ES6 */ && node.kind === 203 /* ForOfStatement */) { emitLoop(node, emitDownLevelForOfStatementWorker); } else { @@ -33174,7 +33808,7 @@ var ts; var endPos = emitToken(86 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 214 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); @@ -33184,7 +33818,7 @@ var ts; else { emit(node.initializer); } - if (node.kind === 200 /* ForInStatement */) { + if (node.kind === 202 /* ForInStatement */) { write(" in "); } else { @@ -33193,15 +33827,12 @@ var ts; emit(node.expression); emitToken(18 /* CloseParenToken */, node.expression.end); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } - function emitDownLevelForOfStatement(node) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } function emitDownLevelForOfStatementWorker(node, loop) { // The following ES6 code: // @@ -33277,7 +33908,7 @@ var ts; // let v = _a[_i]; var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 214 /* VariableDeclarationList */) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -33307,7 +33938,7 @@ var ts; // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. var assignmentExpression = createBinaryExpression(node.initializer, 56 /* EqualsToken */, rhsIterationValue, /*startsOnNewLine*/ false); - if (node.initializer.kind === 164 /* ArrayLiteralExpression */ || node.initializer.kind === 165 /* ObjectLiteralExpression */) { + if (node.initializer.kind === 166 /* ArrayLiteralExpression */ || node.initializer.kind === 167 /* ObjectLiteralExpression */) { // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash. emitDestructuring(assignmentExpression, /*isAssignmentExpressionStatement*/ true, /*value*/ undefined); @@ -33320,10 +33951,10 @@ var ts; write(";"); if (loop) { writeLine(); - emitConvertedLoopCall(loop, /* emitAsBlock */ false); + emitConvertedLoopCall(loop, /*emitAsBlock*/ false); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ false); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ false); } writeLine(); decreaseIndent(); @@ -33335,12 +33966,12 @@ var ts; // it is possible if either // - break\continue is statement labeled and label is located inside the converted loop // - break\continue is non-labeled and located in non-converted loop\switch statement - var jump = node.kind === 203 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 205 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { if (!node.label) { - if (node.kind === 203 /* BreakStatement */) { + if (node.kind === 205 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; write("return \"break\";"); } @@ -33351,20 +33982,20 @@ var ts; } else { var labelMarker; - if (node.kind === 203 /* BreakStatement */) { + if (node.kind === 205 /* BreakStatement */) { labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, /* isBreak */ true, node.label.text, labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); } else { labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, /* isBreak */ false, node.label.text, labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); } write("return \"" + labelMarker + "\";"); } return; } } - emitToken(node.kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); + emitToken(node.kind === 205 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); emitOptional(" ", node.label); write(";"); } @@ -33430,7 +34061,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 241 /* CaseClause */) { + if (node.kind === 243 /* CaseClause */) { write("case "); emit(node.expression); write(":"); @@ -33499,7 +34130,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 218 /* ModuleDeclaration */); + } while (node && node.kind !== 220 /* ModuleDeclaration */); return node; } function emitContainingModuleName(node) { @@ -33524,22 +34155,22 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(8 /* NumericLiteral */); zero.text = "0"; - var result = ts.createSynthesizedNode(177 /* VoidExpression */); + var result = ts.createSynthesizedNode(179 /* VoidExpression */); result.expression = zero; return result; } function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 248 /* SourceFile */) { - ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 227 /* ExportAssignment */); + if (node.parent.kind === 250 /* SourceFile */) { + ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 229 /* ExportAssignment */); // only allow export default at a source file level if (modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */) { if (!isEs6Module) { - if (languageVersion === 1 /* ES5 */) { + if (languageVersion !== 0 /* ES3 */) { // default value of configurable, enumerable, writable are `false`. write("Object.defineProperty(exports, \"__esModule\", { value: true });"); writeLine(); } - else if (languageVersion === 0 /* ES3 */) { + else { write("exports.__esModule = true;"); writeLine(); } @@ -33636,7 +34267,7 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(name); write("\", "); } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 /* VariableDeclaration */ || name.parent.kind === 163 /* BindingElement */); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 213 /* VariableDeclaration */ || name.parent.kind === 165 /* BindingElement */); if (isVariableDeclarationOrBindingElement) { emitModuleMemberName(name.parent); } @@ -33670,7 +34301,7 @@ var ts; // Also temporary variables should be explicitly allocated for source level declarations when module target is system // because actual variable declarations are hoisted var canDefineTempVariablesInPlace = false; - if (root.kind === 211 /* VariableDeclaration */) { + if (root.kind === 213 /* VariableDeclaration */) { var isExported = ts.getCombinedNodeFlags(root) & 2 /* Export */; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; @@ -33678,7 +34309,7 @@ var ts; else if (root.kind === 138 /* Parameter */) { canDefineTempVariablesInPlace = true; } - if (root.kind === 181 /* BinaryExpression */) { + if (root.kind === 183 /* BinaryExpression */) { emitAssignmentExpression(root); } else { @@ -33707,14 +34338,14 @@ var ts; // we need to generate a temporary variable value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); // Return the expression 'value === void 0 ? defaultValue : value' - var equals = ts.createSynthesizedNode(181 /* BinaryExpression */); + var equals = ts.createSynthesizedNode(183 /* BinaryExpression */); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(32 /* EqualsEqualsEqualsToken */); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(182 /* ConditionalExpression */); + var cond = ts.createSynthesizedNode(184 /* ConditionalExpression */); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(53 /* QuestionToken */); cond.whenTrue = whenTrue; @@ -33731,7 +34362,7 @@ var ts; var index; var nameIsComputed = propName.kind === 136 /* ComputedPropertyName */; if (nameIsComputed) { - index = ensureIdentifier(propName.expression, /* reuseIdentifierExpression */ false); + index = ensureIdentifier(propName.expression, /*reuseIdentifierExpressions*/ false); } else { // We create a synthetic copy of the identifier in order to avoid the rewriting that might @@ -33744,7 +34375,7 @@ var ts; : createElementAccessExpression(object, index); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(168 /* CallExpression */); + var call = ts.createSynthesizedNode(170 /* CallExpression */); var sliceIdentifier = ts.createSynthesizedNode(69 /* Identifier */); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -33761,9 +34392,9 @@ var ts; } for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { var p = properties_5[_a]; - if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { + if (p.kind === 247 /* PropertyAssignment */ || p.kind === 248 /* ShorthandPropertyAssignment */) { var propName = p.name; - var target_1 = p.kind === 246 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; + var target_1 = p.kind === 248 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName)); } } @@ -33777,8 +34408,8 @@ var ts; } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187 /* OmittedExpression */) { - if (e.kind !== 185 /* SpreadElementExpression */) { + if (e.kind !== 189 /* OmittedExpression */) { + if (e.kind !== 187 /* SpreadElementExpression */) { emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); } else if (i === elements.length - 1) { @@ -33788,20 +34419,20 @@ var ts; } } function emitDestructuringAssignment(target, value) { - if (target.kind === 246 /* ShorthandPropertyAssignment */) { + if (target.kind === 248 /* ShorthandPropertyAssignment */) { if (target.objectAssignmentInitializer) { value = createDefaultValueCheck(value, target.objectAssignmentInitializer); } target = target.name; } - else if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + else if (target.kind === 183 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { value = createDefaultValueCheck(value, target.right); target = target.left; } - if (target.kind === 165 /* ObjectLiteralExpression */) { + if (target.kind === 167 /* ObjectLiteralExpression */) { emitObjectLiteralAssignment(target, value); } - else if (target.kind === 164 /* ArrayLiteralExpression */) { + else if (target.kind === 166 /* ArrayLiteralExpression */) { emitArrayLiteralAssignment(target, value); } else { @@ -33819,14 +34450,14 @@ var ts; emitDestructuringAssignment(target, value); } else { - if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + if (root.parent.kind !== 174 /* ParenthesizedExpression */) { write("("); } value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); emitDestructuringAssignment(target, value); write(", "); emit(value); - if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + if (root.parent.kind !== 174 /* ParenthesizedExpression */) { write(")"); } } @@ -33853,12 +34484,12 @@ var ts; } for (var i = 0; i < numElements; i++) { var element = elements[i]; - if (pattern.kind === 161 /* ObjectBindingPattern */) { + if (pattern.kind === 163 /* ObjectBindingPattern */) { // Rewrite element to a declaration with an initializer that fetches property var propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } - else if (element.kind !== 187 /* OmittedExpression */) { + else if (element.kind !== 189 /* OmittedExpression */) { if (!element.dotDotDotToken) { // Rewrite element to a declaration that accesses array element at index i emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); @@ -33898,8 +34529,8 @@ var ts; (getCombinedFlagsForIdentifier(node.name) & 8192 /* Let */); // NOTE: default initialization should not be added to let bindings in for-in\for-of statements if (isLetDefinedInLoop && - node.parent.parent.kind !== 200 /* ForInStatement */ && - node.parent.parent.kind !== 201 /* ForOfStatement */) { + node.parent.parent.kind !== 202 /* ForInStatement */ && + node.parent.parent.kind !== 203 /* ForOfStatement */) { initializer = createVoidZero(); } } @@ -33917,7 +34548,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 187 /* OmittedExpression */) { + if (node.kind === 189 /* OmittedExpression */) { return; } var name = node.name; @@ -33929,7 +34560,7 @@ var ts; } } function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 211 /* VariableDeclaration */ && node.parent.kind !== 163 /* BindingElement */)) { + if (!node.parent || (node.parent.kind !== 213 /* VariableDeclaration */ && node.parent.kind !== 165 /* BindingElement */)) { return 0; } return ts.getCombinedNodeFlags(node.parent); @@ -33937,7 +34568,7 @@ var ts; function isES6ExportedDeclaration(node) { return !!(node.flags & 2 /* Export */) && modulekind === 5 /* ES6 */ && - node.parent.kind === 248 /* SourceFile */; + node.parent.kind === 250 /* SourceFile */; } function emitVariableStatement(node) { var startIsEmitted = false; @@ -33988,12 +34619,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2 /* ES6 */) { if (ts.isBindingPattern(node.name)) { - var name_25 = createTempVariable(0 /* Auto */); + var name_23 = createTempVariable(0 /* Auto */); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_25); - emit(name_25); + tempParameters.push(name_23); + emit(name_23); } else { emit(node.name); @@ -34103,7 +34734,7 @@ var ts; emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 174 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; + return node.kind === 176 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; } function emitDeclarationName(node) { if (node.name) { @@ -34114,13 +34745,13 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 173 /* FunctionExpression */) { + if (node.kind === 175 /* FunctionExpression */) { // Emit name if one is present return !!node.name; } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 215 /* FunctionDeclaration */) { // Emit name if one is present, or emit generated name in down-level case (for export default case) - return !!node.name || languageVersion < 2 /* ES6 */; + return !!node.name || modulekind !== 5 /* ES6 */; } } function emitFunctionDeclaration(node) { @@ -34129,20 +34760,29 @@ var ts; } // TODO (yuisu) : we should not have special cases to condition emitting comments // but have one place to fix check for these conditions. - if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */ && - node.parent && node.parent.kind !== 245 /* PropertyAssignment */ && - node.parent.kind !== 168 /* CallExpression */) { - // 1. Methods will emit the comments as part of emitting method declaration + var kind = node.kind, parent = node.parent; + if (kind !== 143 /* MethodDeclaration */ && + kind !== 142 /* MethodSignature */ && + parent && + parent.kind !== 247 /* PropertyAssignment */ && + parent.kind !== 170 /* CallExpression */ && + parent.kind !== 166 /* ArrayLiteralExpression */) { + // 1. Methods will emit comments at their assignment declaration sites. + // // 2. If the function is a property of object literal, emitting leading-comments - // is done by emitNodeWithoutSourceMap which then call this function. - // In particular, we would like to avoid emit comments twice in following case: - // For example: + // is done by emitNodeWithoutSourceMap which then call this function. + // In particular, we would like to avoid emit comments twice in following case: + // // var obj = { // id: // /*comment*/ () => void // } + // // 3. If the function is an argument in call expression, emitting of comments will be - // taken care of in emit list of arguments inside of emitCallexpression + // taken care of in emit list of arguments inside of 'emitCallExpression'. + // + // 4. If the function is in an array literal, 'emitLinePreservingList' will take care + // of leading comments. emitLeadingComments(node); } emitStart(node); @@ -34165,11 +34805,11 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (modulekind !== 5 /* ES6 */ && node.kind === 213 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) { + if (modulekind !== 5 /* ES6 */ && kind === 215 /* FunctionDeclaration */ && parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } emitEnd(node); - if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) { + if (kind !== 143 /* MethodDeclaration */ && kind !== 142 /* MethodSignature */) { emitTrailingComments(node); } } @@ -34202,7 +34842,7 @@ var ts; } function emitAsyncFunctionBodyForES6(node) { var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 174 /* ArrowFunction */; + var isArrowFunction = node.kind === 176 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -34285,17 +34925,16 @@ var ts; } write(" __awaiter(this"); if (hasLexicalArguments) { - write(", arguments"); + write(", arguments, "); } else { - write(", void 0"); + write(", void 0, "); } if (promiseConstructor) { - write(", "); - emitNodeWithoutSourceMap(promiseConstructor); + emitEntityNameAsExpression(promiseConstructor, /*useFallback*/ false); } else { - write(", Promise"); + write("Promise"); } // Emit the call to __awaiter. if (hasLexicalArguments) { @@ -34322,7 +34961,7 @@ var ts; write(" { }"); } else { - if (node.body.kind === 192 /* Block */) { + if (node.body.kind === 194 /* Block */) { emitBlockFunctionBody(node, node.body); } else { @@ -34348,7 +34987,7 @@ var ts; emitSignatureParameters(node); } var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync && languageVersion === 2 /* ES6 */) { + if (isAsync) { emitAsyncFunctionBodyForES6(node); } else { @@ -34381,14 +35020,13 @@ var ts; write(" "); // Unwrap all type assertions. var current = body; - while (current.kind === 171 /* TypeAssertionExpression */) { + while (current.kind === 173 /* TypeAssertionExpression */) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 165 /* ObjectLiteralExpression */); + emitParenthesizedIf(body, current.kind === 167 /* ObjectLiteralExpression */); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); emitDetachedCommentsAndUpdateCommentsInfo(node.body); @@ -34411,8 +35049,10 @@ var ts; increaseIndent(); writeLine(); emitLeadingComments(node.body); + emitStart(body); write("return "); emit(body); + emitEnd(body); write(";"); emitTrailingComments(node.body); emitTempDeclarations(/*newLine*/ true); @@ -34422,11 +35062,9 @@ var ts; emitStart(node.body); write("}"); emitEnd(node.body); - scopeEmitEnd(); } function emitBlockFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); emitDetachedCommentsAndUpdateCommentsInfo(body.statements); @@ -34455,14 +35093,13 @@ var ts; decreaseIndent(); } emitToken(16 /* CloseBraceToken */, body.statements.end); - scopeEmitEnd(); } function findInitialSuperCall(ctor) { if (ctor.body) { var statement = ctor.body.statements[0]; - if (statement && statement.kind === 195 /* ExpressionStatement */) { + if (statement && statement.kind === 197 /* ExpressionStatement */) { var expr = statement.expression; - if (expr && expr.kind === 168 /* CallExpression */) { + if (expr && expr.kind === 170 /* CallExpression */) { var func = expr.expression; if (func && func.kind === 95 /* SuperKeyword */) { return statement; @@ -34548,7 +35185,7 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 191 /* SemicolonClassElement */) { + if (member.kind === 193 /* SemicolonClassElement */) { writeLine(); write(";"); } @@ -34645,7 +35282,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 191 /* SemicolonClassElement */) { + else if (member.kind === 193 /* SemicolonClassElement */) { writeLine(); write(";"); } @@ -34719,7 +35356,6 @@ var ts; } var startIndex = 0; write(" {"); - scopeEmitStart(node, "constructor"); increaseIndent(); if (ctor) { // Emit all the directive prologues (like "use strict"). These have to come before @@ -34754,7 +35390,7 @@ var ts; emitEnd(baseTypeElement); } } - emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false)); + emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ false)); if (ctor) { var statements = ctor.body.statements; if (superCall) { @@ -34769,7 +35405,6 @@ var ts; } decreaseIndent(); emitToken(16 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); emitEnd(ctor || node); if (ctor) { emitTrailingComments(ctor); @@ -34794,7 +35429,7 @@ var ts; } function emitClassLikeDeclarationForES6AndHigher(node) { var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { if (thisNodeIsDecorated) { // To preserve the correct runtime semantics when decorators are applied to the class, // the emit needs to follow one of the following rules: @@ -34870,8 +35505,8 @@ var ts; // // This keeps the expression as an expression, while ensuring that the static parts // of it have been initialized by the time it is used. - var staticProperties = getInitializedProperties(node, /*static:*/ true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 186 /* ClassExpression */; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 188 /* ClassExpression */; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0 /* Auto */); @@ -34884,7 +35519,7 @@ var ts; // emit name if // - node has a name // - this is default export with static initializers - if ((node.name || (node.flags & 512 /* Default */ && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if ((node.name || (node.flags & 512 /* Default */ && (staticProperties.length > 0 || modulekind !== 5 /* ES6 */))) && !thisNodeIsDecorated) { write(" "); emitDeclarationName(node); } @@ -34895,14 +35530,12 @@ var ts; } write(" {"); increaseIndent(); - scopeEmitStart(node); writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES6AndHigher(node); decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now. // For a decorated class, we need to assign its name (if it has one). This is because we emit // the class as a class expression to avoid the double-binding of the identifier: @@ -34924,7 +35557,7 @@ var ts; var property = staticProperties_1[_a]; write(","); writeLine(); - emitPropertyDeclaration(node, property, /*receiver:*/ tempVariable, /*isExpression:*/ true); + emitPropertyDeclaration(node, property, /*receiver*/ tempVariable, /*isExpression*/ true); } write(","); writeLine(); @@ -34937,27 +35570,37 @@ var ts; emitPropertyDeclarations(node, staticProperties); emitDecoratorsOfClass(node); } - // If this is an exported class, but not on the top level (i.e. on an internal - // module), export it - if (!isES6ExportedDeclaration(node) && (node.flags & 2 /* Export */)) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); + if (!(node.flags & 2 /* Export */)) { + return; } - else if (isES6ExportedDeclaration(node) && (node.flags & 512 /* Default */) && thisNodeIsDecorated) { - // if this is a top level default export of decorated class, write the export after the declaration. - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); + if (modulekind !== 5 /* ES6 */) { + emitExportMemberAssignment(node); + } + else { + // If this is an exported class, but not on the top level (i.e. on an internal + // module), export it + if (node.flags & 512 /* Default */) { + // if this is a top level default export of decorated class, write the export after the declaration. + if (thisNodeIsDecorated) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } + } + else if (node.parent.kind !== 250 /* SourceFile */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emitDeclarationName(node); + emitEnd(node); + write(";"); + } } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { // source file level classes in system modules are hoisted so 'var's for them are already defined if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); @@ -34982,7 +35625,6 @@ var ts; tempParameters = undefined; computedPropertyNamesToGeneratedNames = undefined; increaseIndent(); - scopeEmitStart(node); if (baseTypeNode) { writeLine(); emitStart(baseTypeNode); @@ -34994,7 +35636,7 @@ var ts; writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES5AndLower(node); - emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ true)); + emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ true)); writeLine(); emitDecoratorsOfClass(node); writeLine(); @@ -35013,18 +35655,17 @@ var ts; decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); emitStart(node); - write(")("); + write("("); if (baseTypeNode) { emit(baseTypeNode.expression); } - write(")"); - if (node.kind === 214 /* ClassDeclaration */) { + write("))"); + if (node.kind === 216 /* ClassDeclaration */) { write(";"); } emitEnd(node); - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { emitExportMemberAssignment(node); } } @@ -35042,9 +35683,9 @@ var ts; function emitDecoratorsOfConstructor(node) { var decorators = node.decorators; var constructor = ts.getFirstConstructorWithBody(node); - var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated); + var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); // skip decoration of the constructor if neither it nor its parameters are decorated - if (!decorators && !hasDecoratedParameters) { + if (!decorators && !firstParameterDecorator) { return; } // Emit the call to __decorate. Given the class: @@ -35058,25 +35699,24 @@ var ts; // C = __decorate([dec], C); // writeLine(); - emitStart(node); + emitStart(node.decorators || firstParameterDecorator); emitDeclarationName(node); write(" = __decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); + } emitSerializedTypeMetadata(node, /*leadingComma*/ argumentsWritten >= 0); decreaseIndent(); writeLine(); write("], "); emitDeclarationName(node); - write(");"); - emitEnd(node); + write(")"); + emitEnd(node.decorators || firstParameterDecorator); + write(";"); writeLine(); } function emitDecoratorsOfMembers(node, staticFlag) { @@ -35090,10 +35730,6 @@ var ts; if (!ts.nodeCanBeDecorated(member)) { continue; } - // skip a member if it or any of its parameters are not decorated - if (!ts.nodeOrChildIsDecorated(member)) { - continue; - } // skip an accessor declaration if it is not the first accessor var decorators = void 0; var functionLikeMember = void 0; @@ -35117,6 +35753,11 @@ var ts; functionLikeMember = member; } } + var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); + // skip a member if it or any of its parameters are not decorated + if (!decorators && !firstParameterDecorator) { + continue; + } // Emit the call to __decorate. Given the following: // // class C { @@ -35148,26 +35789,22 @@ var ts; // ], C.prototype, "prop"); // writeLine(); - emitStart(member); + emitStart(decorators || firstParameterDecorator); write("__decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + } emitSerializedTypeMetadata(member, argumentsWritten > 0); decreaseIndent(); writeLine(); write("], "); - emitStart(member.name); emitClassMemberPrefix(node, member); write(", "); emitExpressionForPropertyName(member.name); - emitEnd(member.name); if (languageVersion > 0 /* ES3 */) { if (member.kind !== 141 /* PropertyDeclaration */) { // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. @@ -35180,8 +35817,9 @@ var ts; write(", void 0"); } } - write(");"); - emitEnd(member); + write(")"); + emitEnd(decorators || firstParameterDecorator); + write(";"); writeLine(); } } @@ -35194,15 +35832,13 @@ var ts; if (ts.nodeIsDecorated(parameter)) { var decorators = parameter.decorators; argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); write("__param(" + parameterIndex + ", "); emit(decorator.expression); write(")"); - emitEnd(decorator); }); leadingComma = true; } - ++parameterIndex; + parameterIndex++; } } return argumentsWritten; @@ -35235,7 +35871,7 @@ var ts; // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch (node.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: case 143 /* MethodDeclaration */: case 146 /* SetAccessor */: return true; @@ -35255,7 +35891,7 @@ var ts; // // For rules on serializing type annotations, see `serializeTypeNode`. switch (node.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: write("Function"); return; case 141 /* PropertyDeclaration */: @@ -35299,7 +35935,7 @@ var ts; write("Boolean"); return; case 130 /* StringKeyword */: - case 9 /* StringLiteral */: + case 162 /* StringLiteralType */: write("String"); return; case 128 /* NumberKeyword */: @@ -35316,6 +35952,7 @@ var ts; case 158 /* UnionType */: case 159 /* IntersectionType */: case 117 /* AnyKeyword */: + case 161 /* ThisType */: break; default: ts.Debug.fail("Cannot serialize unexpected type node."); @@ -35331,8 +35968,7 @@ var ts; location = location.parent; } // Clone the type name and parent it to a location outside of the current declaration. - var typeName = ts.cloneEntityName(node.typeName); - typeName.parent = location; + var typeName = ts.cloneEntityName(node.typeName, location); var result = resolver.getTypeReferenceSerializationKind(typeName); switch (result) { case ts.TypeReferenceSerializationKind.Unknown: @@ -35389,7 +36025,7 @@ var ts; // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. if (node) { var valueDeclaration; - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -35484,9 +36120,10 @@ var ts; } if (!shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted - if (!(node.flags & 2 /* Export */) || isES6ExportedDeclaration(node)) { + var isES6ExportedEnum = isES6ExportedDeclaration(node); + if (!(node.flags & 2 /* Export */) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 219 /* EnumDeclaration */))) { emitStart(node); - if (isES6ExportedDeclaration(node)) { + if (isES6ExportedEnum) { write("export "); } write("var "); @@ -35503,12 +36140,10 @@ var ts; emitEnd(node.name); write(") {"); increaseIndent(); - scopeEmitStart(node); emitLines(node.members); decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); write(")("); emitModuleMemberName(node); write(" || ("); @@ -35568,7 +36203,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 220 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -35579,6 +36214,9 @@ var ts; function isModuleMergedWithES6Class(node) { return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 32768 /* LexicalModuleMergesWithClass */); } + function isFirstDeclarationOfKind(node, declarations, kind) { + return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); + } function emitModuleDeclaration(node) { // Emit only if this module is non-ambient. var shouldEmit = shouldEmitModuleDeclaration(node); @@ -35588,15 +36226,18 @@ var ts; var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); if (emitVarForModule) { - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); + var isES6ExportedNamespace = isES6ExportedDeclaration(node); + if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 220 /* ModuleDeclaration */)) { + emitStart(node); + if (isES6ExportedNamespace) { + write("export "); + } + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); } emitStart(node); write("(function ("); @@ -35604,7 +36245,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 219 /* ModuleBlock */) { + if (node.body.kind === 221 /* ModuleBlock */) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; @@ -35620,7 +36261,6 @@ var ts; else { write("{"); increaseIndent(); - scopeEmitStart(node); emitCaptureThisForNodeIfNecessary(node); writeLine(); emit(node.body); @@ -35628,7 +36268,6 @@ var ts; writeLine(); var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; emitToken(16 /* CloseBraceToken */, moduleBlock.statements.end); - scopeEmitEnd(); } write(")("); // write moduleDecl = containingModule.m only if it is not exported es6 module member @@ -35682,16 +36321,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 223 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 226 /* NamespaceImport */) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 222 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 224 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -35719,7 +36358,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 226 /* NamespaceImport */) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -35745,7 +36384,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 2 /* Export */) !== 0; + var isExportedImport = node.kind === 223 /* ImportEqualsDeclaration */ && (node.flags & 2 /* Export */) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (modulekind !== 2 /* AMD */) { emitLeadingComments(node); @@ -35764,7 +36403,7 @@ var ts; // import { x, y } from "foo" // import d, * as x from "foo" // import d, { x, y } from "foo" - var isNakedImport = 222 /* ImportDeclaration */ && !node.importClause; + var isNakedImport = 224 /* ImportDeclaration */ && !node.importClause; if (!isNakedImport) { write("var "); write(getGeneratedNameForNode(node)); @@ -35882,15 +36521,17 @@ var ts; } else { // export * from "foo" - writeLine(); - write("__export("); - if (modulekind !== 2 /* AMD */) { - emitRequire(ts.getExternalModuleName(node)); + if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + writeLine(); + write("__export("); + if (modulekind !== 2 /* AMD */) { + emitRequire(ts.getExternalModuleName(node)); + } + else { + write(generatedName); + } + write(");"); } - else { - write(generatedName); - } - write(");"); } emitEnd(node); } @@ -35941,8 +36582,8 @@ var ts; write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 213 /* FunctionDeclaration */ && - expression.kind !== 214 /* ClassDeclaration */) { + if (expression.kind !== 215 /* FunctionDeclaration */ && + expression.kind !== 216 /* ClassDeclaration */) { write(";"); } emitEnd(node); @@ -35975,11 +36616,11 @@ var ts; externalImports = []; exportSpecifiers = {}; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { // import "mod" @@ -35989,18 +36630,20 @@ var ts; externalImports.push(node); } break; - case 221 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 232 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { + case 223 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 234 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { // import x = require("mod") where x is referenced externalImports.push(node); } break; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" - externalImports.push(node); - hasExportStars = true; + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } } else if (resolver.isValueAliasDeclaration(node)) { // export { x, y } from "mod" where at least one export is a value symbol @@ -36011,12 +36654,12 @@ var ts; // export { x, y } for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_26 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_26] || (exportSpecifiers[name_26] = [])).push(specifier); + var name_24 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_24] || (exportSpecifiers[name_24] = [])).push(specifier); } } break; - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; @@ -36026,7 +36669,7 @@ var ts; } } function emitExportStarHelper() { - if (hasExportStars) { + if (hasExportStarsToExportValues) { writeLine(); write("function __export(m) {"); increaseIndent(); @@ -36042,14 +36685,20 @@ var ts; if (namespaceDeclaration && !isDefaultImport(node)) { return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); } - if (node.kind === 222 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 224 /* ImportDeclaration */ && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 228 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 230 /* ExportDeclaration */ && node.moduleSpecifier) { return getGeneratedNameForNode(node); } } - function getExternalModuleNameText(importNode) { + function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { + if (emitRelativePathAsModuleName) { + var name_25 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_25) { + return "\"" + name_25 + "\""; + } + } var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9 /* StringLiteral */) { return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); @@ -36065,8 +36714,8 @@ var ts; for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { var importNode = externalImports_1[_a]; // do not create variable declaration for exports and imports that lack import clause - var skipNode = importNode.kind === 228 /* ExportDeclaration */ || - (importNode.kind === 222 /* ImportDeclaration */ && !importNode.importClause); + var skipNode = importNode.kind === 230 /* ExportDeclaration */ || + (importNode.kind === 224 /* ImportDeclaration */ && !importNode.importClause); if (skipNode) { continue; } @@ -36088,7 +36737,7 @@ var ts; // should always win over entries with similar names that were added via star exports // to support this we store names of local/indirect exported entries in a set. // this set is used to filter names brought by star expors. - if (!hasExportStars) { + if (!hasExportStarsToExportValues) { // local names set is needed only in presence of star exports return undefined; } @@ -36099,7 +36748,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; - if (externalImport.kind === 228 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 230 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -36115,7 +36764,7 @@ var ts; increaseIndent(); var started = false; if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; ++i) { + for (var i = 0; i < exportedDeclarations.length; i++) { // write name of exported declaration, i.e 'export var x...' writeExportedName(exportedDeclarations[i]); } @@ -36131,7 +36780,7 @@ var ts; } for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 228 /* ExportDeclaration */) { + if (externalImport.kind !== 230 /* ExportDeclaration */) { continue; } var exportDecl = externalImport; @@ -36217,14 +36866,14 @@ var ts; writeLine(); write("var "); var seen = {}; - for (var i = 0; i < hoistedVars.length; ++i) { + for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_27 = local.kind === 69 /* Identifier */ + var name_26 = local.kind === 69 /* Identifier */ ? local : local.name; - if (name_27) { + if (name_26) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables - var text = ts.unescapeIdentifier(name_27.text); + var text = ts.unescapeIdentifier(name_26.text); if (ts.hasProperty(seen, text)) { continue; } @@ -36235,7 +36884,7 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 214 /* ClassDeclaration */ || local.kind === 218 /* ModuleDeclaration */ || local.kind === 217 /* EnumDeclaration */) { + if (local.kind === 216 /* ClassDeclaration */ || local.kind === 220 /* ModuleDeclaration */ || local.kind === 219 /* EnumDeclaration */) { emitDeclarationName(local); } else { @@ -36269,21 +36918,21 @@ var ts; if (node.flags & 4 /* Ambient */) { return; } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 215 /* FunctionDeclaration */) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 217 /* EnumDeclaration */) { + if (node.kind === 219 /* EnumDeclaration */) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -36292,7 +36941,7 @@ var ts; } return; } - if (node.kind === 218 /* ModuleDeclaration */) { + if (node.kind === 220 /* ModuleDeclaration */) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -36301,17 +36950,17 @@ var ts; } return; } - if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) { + if (node.kind === 213 /* VariableDeclaration */ || node.kind === 165 /* BindingElement */) { if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) { - var name_28 = node.name; - if (name_28.kind === 69 /* Identifier */) { + var name_27 = node.name; + if (name_27.kind === 69 /* Identifier */) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_28); + hoistedVars.push(name_27); } else { - ts.forEachChild(name_28, visit); + ts.forEachChild(name_27, visit); } } return; @@ -36342,7 +36991,7 @@ var ts; // if block scoped variables are nested in some another block then // no other functions can use them except ones that are defined at least in the same block return (ts.getCombinedNodeFlags(node) & 24576 /* BlockScoped */) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 248 /* SourceFile */; + ts.getEnclosingBlockScopeContainer(node).kind === 250 /* SourceFile */; } function isCurrentFileSystemExternalModule() { return modulekind === 4 /* System */ && isCurrentFileExternalModule; @@ -36402,7 +37051,7 @@ var ts; } function emitSetters(exportStarFunction, dependencyGroups) { write("setters:["); - for (var i = 0; i < dependencyGroups.length; ++i) { + for (var i = 0; i < dependencyGroups.length; i++) { if (i !== 0) { write(","); } @@ -36417,21 +37066,21 @@ var ts; var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // fall-through - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== ""); writeLine(); // save import into the local write(importVariableName + " = " + parameterName + ";"); writeLine(); break; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== ""); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -36444,7 +37093,7 @@ var ts; write(exportFunctionForFile + "({"); writeLine(); increaseIndent(); - for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) { + for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; i_2++) { if (i_2 !== 0) { write(","); writeLine(); @@ -36461,6 +37110,8 @@ var ts; write("});"); } else { + // collectExternalModuleInfo prefilters star exports to keep only ones that export values + // this means that check 'resolver.moduleExportsSomeValue' is redundant and can be omitted here writeLine(); // export * from 'foo' // emit as: @@ -36481,17 +37132,17 @@ var ts; write("execute: function() {"); increaseIndent(); writeLine(); - for (var i = startIndex; i < node.statements.length; ++i) { + for (var i = startIndex; i < node.statements.length; i++) { var statement = node.statements[i]; switch (statement.kind) { // - function declarations are not emitted because they were already hoisted // - import declarations are not emitted since they are already handled in setters // - export declarations with module specifiers are not emitted since they were already written in setters // - export declarations without module specifiers are emitted preserving the order - case 213 /* FunctionDeclaration */: - case 222 /* ImportDeclaration */: + case 215 /* FunctionDeclaration */: + case 224 /* ImportDeclaration */: continue; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: if (!statement.moduleSpecifier) { for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { var element = _b[_a]; @@ -36500,7 +37151,7 @@ var ts; } } continue; - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { // - import equals declarations that import external modules are not emitted continue; @@ -36540,8 +37191,8 @@ var ts; write("["); var groupIndices = {}; var dependencyGroups = []; - for (var i = 0; i < externalImports.length; ++i) { - var text = getExternalModuleNameText(externalImports[i]); + for (var i = 0; i < externalImports.length; i++) { + var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); if (ts.hasProperty(groupIndices, text)) { // deduplicate/group entries in dependency list by the dependency name var groupIndex = groupIndices[text]; @@ -36555,18 +37206,12 @@ var ts; if (i !== 0) { write(", "); } - if (emitRelativePathAsModuleName) { - var name_29 = getExternalModuleNameFromDeclaration(host, resolver, externalImports[i]); - if (name_29) { - text = "\"" + name_29 + "\""; - } - } write(text); } write("], function(" + exportFunctionForFile + ") {"); writeLine(); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitSystemModuleBody(node, dependencyGroups, startIndex); @@ -36596,13 +37241,7 @@ var ts; for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { var importNode = externalImports_4[_c]; // Find the name of the external module - var externalModuleName = getExternalModuleNameText(importNode); - if (emitRelativePathAsModuleName) { - var name_30 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_30) { - externalModuleName = "\"" + name_30 + "\""; - } - } + var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); // Find the name of the module alias, if there is one var importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { @@ -36662,7 +37301,7 @@ var ts; writeModuleName(node, emitRelativePathAsModuleName); emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36673,7 +37312,7 @@ var ts; write("});"); } function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false, /*ensureUseStrict*/ true); emitEmitHelpers(node); collectExternalModuleInfo(node); emitExportStarHelper(); @@ -36693,7 +37332,7 @@ var ts; writeLines(" }\n})("); emitAMDFactoryHeader(dependencyNames); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36707,7 +37346,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); @@ -36770,7 +37409,9 @@ var ts; // Replace entities like   result = result.replace(/&(\w+);/g, function (s, m) { if (entities[m] !== undefined) { - return String.fromCharCode(entities[m]); + var ch = String.fromCharCode(entities[m]); + // " needs to be escaped + return ch === "\"" ? "\\\"" : ch; } else { return s; @@ -36822,24 +37463,41 @@ var ts; } } } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { + function isUseStrictPrologue(node) { + return !!node.expression.text.match(/use strict/); + } + function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { + if (writeUseStrict) { + if (startWithNewLine) { + writeLine(); + } + write("\"use strict\";"); + } + } + function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { + var foundUseStrict = false; + for (var i = 0; i < statements.length; i++) { if (ts.isPrologueDirective(statements[i])) { + if (isUseStrictPrologue(statements[i])) { + foundUseStrict = true; + } if (startWithNewLine || i > 0) { writeLine(); } emit(statements[i]); } else { + ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); // return index of the first non prologue directive return i; } } + ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); return statements.length; } function writeLines(text) { var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; ++i) { + for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (line.length) { writeLine(); @@ -36879,7 +37537,7 @@ var ts; emitShebang(); emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - if (root || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { + if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */]; emitModule(node); } @@ -36893,7 +37551,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36901,6 +37559,9 @@ var ts; } emitLeadingComments(node.endOfFileToken); } + function emit(node) { + emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); + } function emitNodeWithCommentsAndWithoutSourcemap(node) { emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); } @@ -36923,6 +37584,13 @@ var ts; } } } + function emitNodeWithSourceMap(node) { + if (node) { + emitStart(node); + emitNodeWithoutSourceMap(node); + emitEnd(node); + } + } function emitNodeWithoutSourceMap(node) { if (node) { emitJavaScriptWorker(node); @@ -36932,24 +37600,24 @@ var ts; switch (node.kind) { // All of these entities are emitted in a specialized fashion. As such, we allow // the specialized methods for each to handle the comments on the nodes. - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 227 /* ExportAssignment */: + case 217 /* InterfaceDeclaration */: + case 215 /* FunctionDeclaration */: + case 224 /* ImportDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 229 /* ExportAssignment */: return true; } } function shouldEmitLeadingAndTrailingComments(node) { switch (node.kind) { - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: // Only emit the leading/trailing comments for a module if we're actually // emitting the module as well. return shouldEmitModuleDeclaration(node); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: // Only emit the leading/trailing comments for an enum if we're actually // emitting the module as well. return shouldEmitEnumDeclaration(node); @@ -36961,9 +37629,9 @@ var ts; // then we don't want to emit comments when we emit the body. It will have already // been taken care of when we emitted the 'return' statement for the function // expression body. - if (node.kind !== 192 /* Block */ && + if (node.kind !== 194 /* Block */ && node.parent && - node.parent.kind === 174 /* ArrowFunction */ && + node.parent.kind === 176 /* ArrowFunction */ && node.parent.body === node && compilerOptions.target <= 1 /* ES5 */) { return false; @@ -37002,142 +37670,142 @@ var ts; case 13 /* TemplateMiddle */: case 14 /* TemplateTail */: return emitLiteral(node); - case 183 /* TemplateExpression */: + case 185 /* TemplateExpression */: return emitTemplateExpression(node); - case 190 /* TemplateSpan */: + case 192 /* TemplateSpan */: return emitTemplateSpan(node); - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: + case 235 /* JsxElement */: + case 236 /* JsxSelfClosingElement */: return emitJsxElement(node); - case 236 /* JsxText */: + case 238 /* JsxText */: return emitJsxText(node); - case 240 /* JsxExpression */: + case 242 /* JsxExpression */: return emitJsxExpression(node); case 135 /* QualifiedName */: return emitQualifiedName(node); - case 161 /* ObjectBindingPattern */: + case 163 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 162 /* ArrayBindingPattern */: + case 164 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 163 /* BindingElement */: + case 165 /* BindingElement */: return emitBindingElement(node); - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return emitArrayLiteral(node); - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return emitObjectLiteral(node); - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 246 /* ShorthandPropertyAssignment */: + case 248 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); case 136 /* ComputedPropertyName */: return emitComputedPropertyName(node); - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: return emitPropertyAccess(node); - case 167 /* ElementAccessExpression */: + case 169 /* ElementAccessExpression */: return emitIndexedAccess(node); - case 168 /* CallExpression */: + case 170 /* CallExpression */: return emitCallExpression(node); - case 169 /* NewExpression */: + case 171 /* NewExpression */: return emitNewExpression(node); - case 170 /* TaggedTemplateExpression */: + case 172 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 171 /* TypeAssertionExpression */: + case 173 /* TypeAssertionExpression */: return emit(node.expression); - case 189 /* AsExpression */: + case 191 /* AsExpression */: return emit(node.expression); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return emitParenExpression(node); - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return emitFunctionDeclaration(node); - case 175 /* DeleteExpression */: + case 177 /* DeleteExpression */: return emitDeleteExpression(node); - case 176 /* TypeOfExpression */: + case 178 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 177 /* VoidExpression */: + case 179 /* VoidExpression */: return emitVoidExpression(node); - case 178 /* AwaitExpression */: + case 180 /* AwaitExpression */: return emitAwaitExpression(node); - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 180 /* PostfixUnaryExpression */: + case 182 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return emitBinaryExpression(node); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return emitConditionalExpression(node); - case 185 /* SpreadElementExpression */: + case 187 /* SpreadElementExpression */: return emitSpreadElementExpression(node); - case 184 /* YieldExpression */: + case 186 /* YieldExpression */: return emitYieldExpression(node); - case 187 /* OmittedExpression */: + case 189 /* OmittedExpression */: return; - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 194 /* Block */: + case 221 /* ModuleBlock */: return emitBlock(node); - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return emitVariableStatement(node); - case 194 /* EmptyStatement */: + case 196 /* EmptyStatement */: return write(";"); - case 195 /* ExpressionStatement */: + case 197 /* ExpressionStatement */: return emitExpressionStatement(node); - case 196 /* IfStatement */: + case 198 /* IfStatement */: return emitIfStatement(node); - case 197 /* DoStatement */: + case 199 /* DoStatement */: return emitDoStatement(node); - case 198 /* WhileStatement */: + case 200 /* WhileStatement */: return emitWhileStatement(node); - case 199 /* ForStatement */: + case 201 /* ForStatement */: return emitForStatement(node); - case 201 /* ForOfStatement */: - case 200 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 202 /* ForInStatement */: return emitForInOrForOfStatement(node); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 204 /* ContinueStatement */: + case 205 /* BreakStatement */: return emitBreakOrContinueStatement(node); - case 204 /* ReturnStatement */: + case 206 /* ReturnStatement */: return emitReturnStatement(node); - case 205 /* WithStatement */: + case 207 /* WithStatement */: return emitWithStatement(node); - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: return emitSwitchStatement(node); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: return emitCaseOrDefaultClause(node); - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: return emitLabeledStatement(node); - case 208 /* ThrowStatement */: + case 210 /* ThrowStatement */: return emitThrowStatement(node); - case 209 /* TryStatement */: + case 211 /* TryStatement */: return emitTryStatement(node); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return emitCatchClause(node); - case 210 /* DebuggerStatement */: + case 212 /* DebuggerStatement */: return emitDebuggerStatement(node); - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: return emitClassExpression(node); - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: return emitClassDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 247 /* EnumMember */: + case 249 /* EnumMember */: return emitEnumMember(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: return emitImportDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return emitExportDeclaration(node); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return emitExportAssignment(node); - case 248 /* SourceFile */: + case 250 /* SourceFile */: return emitSourceFileNode(node); } } @@ -37176,7 +37844,7 @@ var ts; function getLeadingCommentsToEmit(node) { // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments if (node.parent) { - if (node.parent.kind === 248 /* SourceFile */ || node.pos !== node.parent.pos) { + if (node.parent.kind === 250 /* SourceFile */ || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { // get comments without detached comments return getLeadingCommentsWithoutDetachedComments(); @@ -37191,7 +37859,7 @@ var ts; function getTrailingCommentsToEmit(node) { // Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments if (node.parent) { - if (node.parent.kind === 248 /* SourceFile */ || node.end !== node.parent.end) { + if (node.parent.kind === 250 /* SourceFile */ || node.end !== node.parent.end) { return ts.getTrailingCommentRanges(currentText, node.end); } } @@ -37200,10 +37868,10 @@ var ts; * Emit comments associated with node that will not be emitted into JS file */ function emitCommentsOnNotEmittedNode(node) { - emitLeadingCommentsWorker(node, /*isEmittedNode:*/ false); + emitLeadingCommentsWorker(node, /*isEmittedNode*/ false); } function emitLeadingComments(node) { - return emitLeadingCommentsWorker(node, /*isEmittedNode:*/ true); + return emitLeadingCommentsWorker(node, /*isEmittedNode*/ true); } function emitLeadingCommentsWorker(node, isEmittedNode) { if (compilerOptions.removeComments) { @@ -37228,7 +37896,7 @@ var ts; } ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); } function emitTrailingComments(node) { if (compilerOptions.removeComments) { @@ -37280,18 +37948,31 @@ var ts; } } } + function writeComment(text, lineMap, writer, comment, newLine) { + emitPos(comment.pos); + ts.writeCommentRange(text, lineMap, writer, comment, newLine); + emitPos(comment.end); + } function emitShebang() { var shebang = ts.getShebang(currentText); if (shebang) { write(shebang); + writeLine(); } } var _a, _b; } - function emitFile(jsFilePath, sourceFile) { - emitJavaScript(jsFilePath, sourceFile); - if (compilerOptions.declaration) { - ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics); + function emitFile(_a, sourceFiles, isBundledEmit) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + // Make sure not to write js File and source map file if any of them cannot be written + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; + } + if (declarationFilePath) { + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } } } @@ -37309,10 +37990,10 @@ var ts; /** The version of the TypeScript compiler release */ var emptyArray = []; ts.version = "1.8.0"; - function findConfigFile(searchPath) { + function findConfigFile(searchPath, fileExists) { var fileName = "tsconfig.json"; while (true) { - if (ts.sys.fileExists(fileName)) { + if (fileExists(fileName)) { return fileName; } var parentPath = ts.getDirectoryPath(searchPath); @@ -37336,21 +38017,22 @@ var ts; ? compilerOptions.moduleResolution : compilerOptions.module === 1 /* CommonJS */ ? 2 /* NodeJs */ : 1 /* Classic */; switch (moduleResolution) { - case 2 /* NodeJs */: return nodeModuleNameResolver(moduleName, containingFile, host); + case 2 /* NodeJs */: return nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); case 1 /* Classic */: return classicNameResolver(moduleName, containingFile, compilerOptions, host); } } ts.resolveModuleName = resolveModuleName; - function nodeModuleNameResolver(moduleName, containingFile, host) { + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { var failedLookupLocations = []; var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolvedFileName = loadNodeModuleFromFile(ts.supportedJsExtensions, candidate, failedLookupLocations, host); + var resolvedFileName = loadNodeModuleFromFile(supportedExtensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, host); if (resolvedFileName) { return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }; } - resolvedFileName = loadNodeModuleFromDirectory(ts.supportedJsExtensions, candidate, failedLookupLocations, host); + resolvedFileName = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, host); return resolvedFileName ? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations } : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; @@ -37360,11 +38042,21 @@ var ts; } } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, host) { + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * 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 loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, onlyRecordFailures, host) { return ts.forEach(extensions, tryLoad); function tryLoad(ext) { var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (host.fileExists(fileName)) { + if (!onlyRecordFailures && host.fileExists(fileName)) { return fileName; } else { @@ -37373,9 +38065,10 @@ var ts; } } } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, host) { + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, host) { var packageJsonPath = ts.combinePaths(candidate, "package.json"); - if (host.fileExists(packageJsonPath)) { + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, host); + if (directoryExists && host.fileExists(packageJsonPath)) { var jsonContent; try { var jsonText = host.readFile(packageJsonPath); @@ -37385,8 +38078,9 @@ var ts; // gracefully handle if readFile fails or returns not JSON jsonContent = { typings: undefined }; } - if (jsonContent.typings) { - var result = loadNodeModuleFromFile(extensions, ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host); + if (typeof jsonContent.typings === "string") { + var path = ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)); + var result = loadNodeModuleFromFile(extensions, path, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(path), host), host); if (result) { return result; } @@ -37396,7 +38090,7 @@ var ts; // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results failedLookupLocation.push(packageJsonPath); } - return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, host); + return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, !directoryExists, host); } function loadModuleFromNodeModules(moduleName, directory, host) { var failedLookupLocations = []; @@ -37405,12 +38099,14 @@ var ts; var baseName = ts.getBaseFileName(directory); if (baseName !== "node_modules") { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, host); var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var result = loadNodeModuleFromFile(ts.supportedExtensions, candidate, failedLookupLocations, host); + // Load only typescript files irrespective of allowJs option if loading from node modules + var result = loadNodeModuleFromFile(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; } - result = loadNodeModuleFromDirectory(ts.supportedExtensions, candidate, failedLookupLocations, host); + result = loadNodeModuleFromDirectory(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; } @@ -37436,10 +38132,10 @@ var ts; var searchName; var failedLookupLocations = []; var referencedSourceFile; - var extensions = compilerOptions.allowNonTsExtensions ? ts.supportedJsExtensions : ts.supportedExtensions; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); while (true) { searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - referencedSourceFile = ts.forEach(extensions, function (extension) { + referencedSourceFile = ts.forEach(supportedExtensions, function (extension) { if (extension === ".tsx" && !compilerOptions.jsx) { // resolve .tsx files only if jsx support is enabled // 'logical not' handles both undefined and None cases @@ -37540,14 +38236,15 @@ var ts; getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); } + readFile: function (fileName) { return ts.sys.readFile(fileName); }, + directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); } }; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -37585,8 +38282,11 @@ var ts; var noDiagnosticsTypeChecker; var classifiableNames; var skipDefaultLib = options.noLib; + var supportedExtensions = ts.getSupportedExtensions(options); var start = new Date().getTime(); host = host || createCompilerHost(options); + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var currentDirectory = host.getCurrentDirectory(); var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) @@ -37603,24 +38303,23 @@ var ts; (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx)) { + (oldOptions.jsx !== options.jsx) || + (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } if (!tryReuseStructureFromOldProgram()) { - ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // Do not process the default library if: // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. if (!skipDefaultLib) { - processRootFile(host.getDefaultLibFileName(options), true); + processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true); } } - verifyCompilerOptions(); // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; - ts.programTime += new Date().getTime() - start; program = { getRootFileNames: function () { return rootNames; }, getSourceFile: getSourceFile, @@ -37634,7 +38333,7 @@ var ts; getTypeChecker: getTypeChecker, getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, - getCommonSourceDirectory: function () { return commonSourceDirectory; }, + getCommonSourceDirectory: getCommonSourceDirectory, emit: emit, getCurrentDirectory: function () { return currentDirectory; }, getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, @@ -37643,7 +38342,27 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; } }; + verifyCompilerOptions(); + ts.programTime += new Date().getTime() - start; return program; + function getCommonSourceDirectory() { + if (typeof commonSourceDirectory === "undefined") { + if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + // If a rootDir is specified and is valid use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(files); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } function getClassifiableNames() { if (!classifiableNames) { // Initialize a checker so that all our files are bound. @@ -37699,7 +38418,7 @@ var ts; var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct - for (var i = 0; i < moduleNames.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var newResolution = resolutions[i]; var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); var resolutionChanged = oldResolution @@ -37724,7 +38443,7 @@ var ts; newSourceFiles.push(newSourceFile); } // update fileName -> file mapping - for (var i = 0, len = newSourceFiles.length; i < len; ++i) { + for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; @@ -37745,7 +38464,8 @@ var ts; getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFiles: program.getSourceFiles, - writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }) + writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }), + isEmitBlocked: isEmitBlocked }; } function getDiagnosticsProducingTypeChecker() { @@ -37758,12 +38478,18 @@ var ts; var _this = this; return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { // If the noEmitOnError flag is set, then check if we have any errors so far. If so, // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError && getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken).length > 0) { - return { diagnostics: [], sourceMaps: undefined, emitSkipped: true }; + if (options.noEmitOnError) { + var preEmitDiagnostics = getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken); + if (preEmitDiagnostics.length > 0) { + return { diagnostics: preEmitDiagnostics, sourceMaps: undefined, emitSkipped: true }; + } } // Create the emit resolver outside of the "emitTime" tracking code below. That way // any cost associated with it (like type checking) are appropriate associated with @@ -37833,12 +38559,164 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + // For JavaScript files, we don't want to report the normal typescript semantic errors. + // Instead, we just report errors for using TypeScript-only constructs from within a + // JavaScript file. + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? + getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : + typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); } + function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var diagnostics = []; + walk(sourceFile); + return diagnostics; + function walk(node) { + if (!node) { + return false; + } + switch (node.kind) { + case 223 /* ImportEqualsDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return true; + case 229 /* ExportAssignment */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return true; + case 216 /* ClassDeclaration */: + var classDeclaration = node; + if (checkModifiers(classDeclaration.modifiers) || + checkTypeParameters(classDeclaration.typeParameters)) { + return true; + } + break; + case 245 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 106 /* ImplementsKeyword */) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 217 /* InterfaceDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 220 /* ModuleDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 218 /* TypeAliasDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return true; + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 175 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 176 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + var functionDeclaration = node; + if (checkModifiers(functionDeclaration.modifiers) || + checkTypeParameters(functionDeclaration.typeParameters) || + checkTypeAnnotation(functionDeclaration.type)) { + return true; + } + break; + case 195 /* VariableStatement */: + var variableStatement = node; + if (checkModifiers(variableStatement.modifiers)) { + return true; + } + break; + case 213 /* VariableDeclaration */: + var variableDeclaration = node; + if (checkTypeAnnotation(variableDeclaration.type)) { + return true; + } + break; + case 170 /* CallExpression */: + case 171 /* 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)); + return true; + } + break; + case 138 /* 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)); + return true; + } + if (parameter.questionToken) { + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return true; + } + if (parameter.type) { + diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 141 /* PropertyDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 219 /* EnumDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 173 /* TypeAssertionExpression */: + var typeAssertionExpression = node; + diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return true; + case 139 /* Decorator */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); + return true; + } + return ts.forEachChild(node, walk); + } + 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)); + return true; + } + return false; + } + function checkTypeAnnotation(type) { + if (type) { + diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkModifiers(modifiers) { + if (modifiers) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 122 /* DeclareKeyword */: + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + // These are all legal modifiers. + case 113 /* StaticKeyword */: + case 82 /* ExportKeyword */: + case 74 /* ConstKeyword */: + case 77 /* DefaultKeyword */: + case 115 /* AbstractKeyword */: + } + } + } + return false; + } + }); + } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { return runWithCancellationToken(function () { if (!ts.isDeclarationFile(sourceFile)) { @@ -37880,16 +38758,16 @@ var ts; var imports; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; - collect(node, /* allowRelativeModuleNames */ true, /* collectOnlyRequireCalls */ false); + collect(node, /*allowRelativeModuleNames*/ true, /*collectOnlyRequireCalls*/ false); } file.imports = imports || emptyArray; return; function collect(node, allowRelativeModuleNames, collectOnlyRequireCalls) { if (!collectOnlyRequireCalls) { switch (node.kind) { - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: + case 224 /* ImportDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 230 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) { break; @@ -37901,7 +38779,7 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) { // TypeScript 1.0 spec (April 2014): 12.1.6 // An AmbientExternalModuleDeclaration declares an external module. @@ -37912,7 +38790,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 12.1.6 // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules // only through top - level external module names. Relative external module names are not permitted. - collect(node, /* allowRelativeModuleNames */ false, collectOnlyRequireCalls); + collect(node, /*allowRelativeModuleNames*/ false, collectOnlyRequireCalls); }); } break; @@ -37923,7 +38801,7 @@ var ts; (imports || (imports = [])).push(node.arguments[0]); } else { - ts.forEachChild(node, function (node) { return collect(node, allowRelativeModuleNames, /* collectOnlyRequireCalls */ true); }); + ts.forEachChild(node, function (node) { return collect(node, allowRelativeModuleNames, /*collectOnlyRequireCalls*/ true); }); } } } @@ -37932,9 +38810,9 @@ var ts; var diagnosticArgument; var diagnostic; if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; + diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; @@ -37952,7 +38830,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -37977,12 +38855,12 @@ var ts; } } // Get source file from normalized fileName - function findSourceFile(fileName, normalizedAbsolutePath, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(normalizedAbsolutePath)) { - var file_1 = filesByName.get(normalizedAbsolutePath); + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + if (filesByName.contains(path)) { + var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== normalizedAbsolutePath) { + if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } return file_1; @@ -37996,17 +38874,17 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); - filesByName.set(normalizedAbsolutePath, file); + filesByName.set(path, file); if (file) { - file.path = normalizedAbsolutePath; + file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case - var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); + var existingFile = filesByNameIgnoreCase.get(path); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(normalizedAbsolutePath, file); + filesByNameIgnoreCase.set(path, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -38028,7 +38906,7 @@ var ts; function processReferencedFiles(file, basePath) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end); + processSourceFile(referencedFileName, /*isDefaultLib*/ false, file, ref.pos, ref.end); }); } function getCanonicalFileName(fileName) { @@ -38040,15 +38918,17 @@ var ts; file.resolvedModules = {}; var moduleNames = ts.map(file.imports, function (name) { return name.text; }); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); - for (var i = 0; i < file.imports.length; ++i) { + for (var i = 0; i < file.imports.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); if (resolution && !options.noResolve) { - var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /* isDefaultLib */ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { + // Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files, + // this check is ok. Otherwise this would be never true for javascript file if (!ts.isExternalModule(importedFile)) { - var start_2 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_2, file.imports[i].end - start_2, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); + var start_5 = ts.getTokenPosOfNode(file.imports[i], file); + fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { var firstRef = importedFile.referencedFiles[0]; @@ -38066,7 +38946,7 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var commonPathComponents; - ts.forEach(files, function (sourceFile) { + var failed = ts.forEach(files, function (sourceFile) { // Each file contributes into common source file path if (ts.isDeclarationFile(sourceFile)) { return; @@ -38079,10 +38959,10 @@ var ts; return; } for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; + // Failed to find any common path component + return true; } // New common path found that is 0 -> i-1 commonPathComponents.length = i; @@ -38094,6 +38974,10 @@ var ts; commonPathComponents.length = sourcePathComponents.length; } }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } if (!commonPathComponents) { return currentDirectory; } @@ -38103,8 +38987,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -38138,14 +39022,14 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); } - if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap")); - } } if (options.inlineSources) { if (!options.sourceMap && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); } + if (options.sourceRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); + } } if (options.out && options.outFile) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); @@ -38155,10 +39039,9 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } - if (options.sourceRoot) { + if (options.sourceRoot && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); } - return; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; @@ -38176,7 +39059,7 @@ var ts; else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && !options.module) { // 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_compile_modules_unless_the_module_flag_is_provided)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } // Cannot specify module gen target of es6 when below es6 if (options.module === 5 /* ES6 */ && languageVersion < 2 /* ES6 */) { @@ -38191,19 +39074,11 @@ var ts; if (options.outDir || options.sourceRoot || options.mapRoot) { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { - // If a rootDir is specified and is valid use it as the commonSourceDirectory - commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); - } - else { - // Compute the commonSourceDirectory from the input files - commonSourceDirectory = computeCommonSourceDirectory(files); - } - if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { - // Make sure directory path ends with directory separator so this string can directly - // used to replace with "" to get the relative path of the source file and the relative path doesn't - // start with / making it rooted path - commonSourceDirectory += ts.directorySeparator; + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { @@ -38220,10 +39095,47 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } + else if (options.allowJs && options.declaration) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } + if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit) { + var emitHost = getEmitHost(); + var emitFilesSeen = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); + // Report error if the output overwrites input file + if (filesByName.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + } + // Report error if multiple files write into same file + if (emitFilesSeen.contains(emitFilePath)) { + // Already seen the same emit file - report error + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + } + else { + emitFilesSeen.set(emitFilePath, true); + } + } + } + } + function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); } } ts.createProgram = createProgram; @@ -38284,6 +39196,11 @@ var ts; description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, error: ts.Diagnostics.Argument_for_jsx_must_be_preserve_or_react }, + { + name: "reactNamespace", + type: "string", + description: ts.Diagnostics.Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit + }, { name: "listFiles", type: "boolean" @@ -38509,6 +39426,16 @@ var ts; name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "allowJs", + type: "boolean", + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled } ]; var optionNameMapCache; @@ -38543,7 +39470,8 @@ var ts; function parseStrings(args) { var i = 0; while (i < args.length) { - var s = args[i++]; + var s = args[i]; + i++; if (s.charCodeAt(0) === 64 /* at */) { parseResponseFile(s.slice(1)); } @@ -38561,20 +39489,23 @@ var ts; } switch (opt.type) { case "number": - options[opt.name] = parseInt(args[i++]); + options[opt.name] = parseInt(args[i]); + i++; break; case "boolean": options[opt.name] = true; break; case "string": - options[opt.name] = args[i++] || ""; + options[opt.name] = args[i] || ""; + i++; break; // If not a primitive, the possible types are specified in what is effectively a map of options. default: - var map_2 = opt.type; - var key = (args[i++] || "").toLowerCase(); - if (ts.hasProperty(map_2, key)) { - options[opt.name] = map_2[key]; + var map_1 = opt.type; + var key = (args[i] || "").toLowerCase(); + i++; + if (ts.hasProperty(map_1, key)) { + options[opt.name] = map_1[key]; } else { errors.push(ts.createCompilerDiagnostic(opt.error)); @@ -38687,8 +39618,10 @@ var ts; * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json, host, basePath) { - var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors; + function parseJsonConfigFileContent(json, host, basePath, existingOptions) { + if (existingOptions === void 0) { existingOptions = {}; } + var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), optionsFromJsonConfigFile = _a.options, errors = _a.errors; + var options = ts.extend(existingOptions, optionsFromJsonConfigFile); return { options: options, fileNames: getFileNames(), @@ -38705,23 +39638,31 @@ var ts; } } else { + var filesSeen = {}; var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; - var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); - for (var i = 0; i < sysFiles.length; i++) { - var name_31 = sysFiles[i]; - if (ts.fileExtensionIs(name_31, ".d.ts")) { - var baseName = name_31.substr(0, name_31.length - ".d.ts".length); - if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) { - fileNames.push(name_31); + var supportedExtensions = ts.getSupportedExtensions(options); + ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); + // Get files of supported extensions in their order of resolution + for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; + var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); + for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { + var fileName = filesInDirWithExtension_1[_a]; + // .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension, + // lets pick them when its turn comes up + if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { + continue; } - } - else if (ts.fileExtensionIs(name_31, ".ts")) { - if (!ts.contains(sysFiles, name_31 + "x")) { - fileNames.push(name_31); + // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files) + // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation + if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { + var baseName = fileName.substr(0, fileName.length - extension.length); + if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { + continue; + } } - } - else { - fileNames.push(name_31); + filesSeen[fileName] = true; + fileNames.push(fileName); } } } @@ -38845,7 +39786,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 174 /* ArrowFunction */; + return ts.isFunctionBlock(node) && node.parent.kind !== 176 /* ArrowFunction */; } var depth = 0; var maxDepth = 20; @@ -38857,7 +39798,7 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 192 /* Block */: + case 194 /* Block */: if (!ts.isFunctionBlock(n)) { var parent_7 = n.parent; var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); @@ -38865,18 +39806,18 @@ var ts; // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collaps the block, but consider its hint span // to be the entire span of the parent. - if (parent_7.kind === 197 /* DoStatement */ || - parent_7.kind === 200 /* ForInStatement */ || - parent_7.kind === 201 /* ForOfStatement */ || - parent_7.kind === 199 /* ForStatement */ || - parent_7.kind === 196 /* IfStatement */ || - parent_7.kind === 198 /* WhileStatement */ || - parent_7.kind === 205 /* WithStatement */ || - parent_7.kind === 244 /* CatchClause */) { + if (parent_7.kind === 199 /* DoStatement */ || + parent_7.kind === 202 /* ForInStatement */ || + parent_7.kind === 203 /* ForOfStatement */ || + parent_7.kind === 201 /* ForStatement */ || + parent_7.kind === 198 /* IfStatement */ || + parent_7.kind === 200 /* WhileStatement */ || + parent_7.kind === 207 /* WithStatement */ || + parent_7.kind === 246 /* CatchClause */) { addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_7.kind === 209 /* TryStatement */) { + if (parent_7.kind === 211 /* TryStatement */) { // Could be the try-block, or the finally-block. var tryStatement = parent_7; if (tryStatement.tryBlock === n) { @@ -38903,23 +39844,23 @@ var ts; break; } // Fallthrough. - case 219 /* ModuleBlock */: { + case 221 /* ModuleBlock */: { var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 165 /* ObjectLiteralExpression */: - case 220 /* CaseBlock */: { + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: + case 167 /* ObjectLiteralExpression */: + case 222 /* CaseBlock */: { var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); @@ -38949,12 +39890,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_32 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_32); + for (var name_28 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_28); 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_32); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_28); if (!matches) { continue; } @@ -38967,14 +39908,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_32); + matches = patternMatcher.getMatches(containers, name_28); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_32, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_28, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -39013,7 +39954,7 @@ var ts; containers.unshift(text); } else if (declaration.name.kind === 136 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ true); + return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); } else { // Don't know how to add this. @@ -39033,12 +39974,12 @@ var ts; } return true; } - if (expression.kind === 166 /* PropertyAccessExpression */) { + if (expression.kind === 168 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); } - return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion:*/ true); + return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); } return false; } @@ -39047,7 +39988,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. if (declaration.name.kind === 136 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ false)) { + if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -39108,7 +40049,7 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile) { + function getNavigationBarItems(sourceFile, compilerOptions) { // If the source file has any child items, then it included in the tree // and takes lexical ownership of all other top-level items. var hasGlobalNode = false; @@ -39120,17 +40061,17 @@ var ts; var current = node.parent; while (current) { switch (current.kind) { - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: // If we have a module declared as A.B.C, it is more "intuitive" // to say it only has a single layer of depth do { current = current.parent; - } while (current.kind === 218 /* ModuleDeclaration */); + } while (current.kind === 220 /* ModuleDeclaration */); // fall through - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 217 /* InterfaceDeclaration */: + case 215 /* FunctionDeclaration */: indent++; } current = current.parent; @@ -39141,21 +40082,21 @@ var ts; var childNodes = []; function visit(node) { switch (node.kind) { - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: ts.forEach(node.declarationList.declarations, visit); break; - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: + case 163 /* ObjectBindingPattern */: + case 164 /* ArrayBindingPattern */: ts.forEach(node.elements, visit); break; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -39167,7 +40108,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 226 /* NamespaceImport */) { childNodes.push(importClause.namedBindings); } else { @@ -39176,21 +40117,21 @@ var ts; } } break; - case 163 /* BindingElement */: - case 211 /* VariableDeclaration */: + case 165 /* BindingElement */: + case 213 /* VariableDeclaration */: if (ts.isBindingPattern(node.name)) { visit(node.name); break; } // Fall through - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 213 /* FunctionDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 217 /* InterfaceDeclaration */: + case 220 /* ModuleDeclaration */: + case 215 /* FunctionDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 228 /* ImportSpecifier */: + case 232 /* ExportSpecifier */: childNodes.push(node); break; } @@ -39238,17 +40179,17 @@ var ts; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { var node = nodes_4[_i]; switch (node.kind) { - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 217 /* InterfaceDeclaration */: topLevelNodes.push(node); break; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: var moduleDeclaration = node; topLevelNodes.push(node); addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); break; - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: var functionDeclaration = node; if (isTopLevelFunctionDeclaration(functionDeclaration)) { topLevelNodes.push(node); @@ -39259,12 +40200,12 @@ var ts; } } function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 213 /* FunctionDeclaration */) { + if (functionDeclaration.kind === 215 /* FunctionDeclaration */) { // A function declaration is 'top level' if it contains any function declarations // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === 192 /* Block */) { + if (functionDeclaration.body && functionDeclaration.body.kind === 194 /* Block */) { // Proper function declarations can only have identifier names - if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 213 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { + if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 215 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { return true; } // Or if it is not parented by another function. i.e all functions @@ -39341,7 +40282,7 @@ var ts; return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); case 149 /* IndexSignature */: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 247 /* EnumMember */: + case 249 /* EnumMember */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); case 147 /* CallSignature */: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); @@ -39350,18 +40291,18 @@ var ts; case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: var variableDeclarationNode; - var name_33; - if (node.kind === 163 /* BindingElement */) { - name_33 = node.name; + var name_29; + if (node.kind === 165 /* BindingElement */) { + name_29 = node.name; variableDeclarationNode = node; // binding elements are added only for variable declarations // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 211 /* VariableDeclaration */) { + while (variableDeclarationNode && variableDeclarationNode.kind !== 213 /* VariableDeclaration */) { variableDeclarationNode = variableDeclarationNode.parent; } ts.Debug.assert(variableDeclarationNode !== undefined); @@ -39369,24 +40310,24 @@ var ts; else { ts.Debug.assert(!ts.isBindingPattern(node.name)); variableDeclarationNode = node; - name_33 = node.name; + name_29 = node.name; } if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.constElement); + return createItem(node, getTextOfNode(name_29), ts.ScriptElementKind.constElement); } else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.letElement); + return createItem(node, getTextOfNode(name_29), ts.ScriptElementKind.letElement); } else { - return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.variableElement); + return createItem(node, getTextOfNode(name_29), ts.ScriptElementKind.variableElement); } case 144 /* Constructor */: return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 230 /* ExportSpecifier */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: + case 232 /* ExportSpecifier */: + case 228 /* ImportSpecifier */: + case 223 /* ImportEqualsDeclaration */: + case 225 /* ImportClause */: + case 226 /* NamespaceImport */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); } return undefined; @@ -39416,17 +40357,17 @@ var ts; } function createTopLevelItem(node) { switch (node.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: return createSourceFileItem(node); - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: return createClassItem(node); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return createEnumItem(node); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return createIterfaceItem(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return createModuleItem(node); - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: return createFunctionItem(node); } return undefined; @@ -39438,7 +40379,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 220 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -39450,7 +40391,7 @@ var ts; return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } function createFunctionItem(node) { - if (node.body && node.body.kind === 192 /* Block */) { + if (node.body && node.body.kind === 194 /* Block */) { var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } @@ -39504,13 +40445,13 @@ var ts; return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); } function getInnermostModule(node) { - while (node.body.kind === 218 /* ModuleDeclaration */) { + while (node.body.kind === 220 /* ModuleDeclaration */) { node = node.body; } return node; } function getNodeSpan(node) { - return node.kind === 248 /* SourceFile */ + return node.kind === 250 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); } @@ -39542,12 +40483,11 @@ var ts; } function createPatternMatcher(pattern) { // We'll often see the same candidate string many times when searching (For example, when - // 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 + // 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 = {}; pattern = pattern.trim(); - var fullPatternSegment = createSegment(pattern); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); return { @@ -39587,7 +40527,7 @@ var ts; // So far so good. Now break up the container for the candidate and check if all // the dotted parts match up correctly. var totalMatch = candidateMatch; - for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i--, j--) { + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { var segment = dotSeparatedSegments[i]; var containerName = candidateContainers[j]; var containerMatch = matchSegment(containerName, segment); @@ -39626,7 +40566,7 @@ var ts; if (index > 0) { // c) If the part is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring - // match. + // match. // // Note: We only have a substring match if the lowercase part is prefix match of some // word part. That way we don't match something like 'Class' when the user types 'a'. @@ -39666,8 +40606,8 @@ var ts; if (isLowercase) { // f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? // We could check every character boundary start of the candidate for the pattern. However, that's - // an m * n operation in the wost case. Instead, find the first instance of the pattern - // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to // filter the list based on a substring that starts on a capital letter and also with a lowercase one. // (Pattern: fogbar, Candidate: quuxfogbarFogBar). if (chunk.text.length < candidate.length) { @@ -39719,7 +40659,7 @@ var ts; // // c) If the word is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring - // match. + // match. // // Note: We only have a substring match if the lowercase part is prefix match of // some word part. That way we don't match something like 'Class' when the user @@ -39733,7 +40673,7 @@ var ts; // e) If the word was not entirely lowercase, then attempt a camel cased match as // well. // - // f) The word is all lower case. Is it a case insensitive substring of the candidate starting + // f) The word is all lower case. Is it a case insensitive substring of the candidate starting // on a part boundary of the candidate? // // Only if all words have some sort of match is the pattern considered matched. @@ -39783,7 +40723,7 @@ var ts; // Note: we may have more pattern parts than candidate parts. This is because multiple // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U - // and I will both match in UI. + // and I will both match in UI. var currentCandidate = 0; var currentChunkSpan = 0; var firstMatch = undefined; @@ -39812,13 +40752,13 @@ var ts; // Consider the case of matching SiUI against SimpleUIElement. The candidate parts // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to - // still keep matching pattern parts against that candidate part. + // still keep matching pattern parts against that candidate part. for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; if (gotOneMatchThisCandidate) { // We've already gotten one pattern part match in this candidate. We will // only continue trying to consumer pattern parts if the last part and this - // part are both upper case. + // part are both upper case. if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { break; @@ -39848,42 +40788,6 @@ var ts; } } ts.createPatternMatcher = createPatternMatcher; - // Helper function to compare two matches to determine which is better. Matches are first - // ordered by kind (so all prefix matches always beat all substring matches). Then, if the - // match is a camel case match, the relative weights of the match are used to determine - // which is better (with a greater weight being better). Then if the match is of the same - // type, then a case sensitive match is considered better than an insensitive one. - function patternMatchCompareTo(match1, match2) { - return compareType(match1, match2) || - compareCamelCase(match1, match2) || - compareCase(match1, match2) || - comparePunctuation(match1, match2); - } - function comparePunctuation(result1, result2) { - // Consider a match to be better if it was successful without stripping punctuation - // versus a match that had to strip punctuation to succeed. - if (result1.punctuationStripped !== result2.punctuationStripped) { - return result1.punctuationStripped ? 1 : -1; - } - return 0; - } - function compareCase(result1, result2) { - if (result1.isCaseSensitive !== result2.isCaseSensitive) { - return result1.isCaseSensitive ? -1 : 1; - } - return 0; - } - function compareType(result1, result2) { - return result1.kind - result2.kind; - } - function compareCamelCase(result1, result2) { - if (result1.kind === PatternMatchKind.camelCase && result2.kind === PatternMatchKind.camelCase) { - // Swap the values here. If result1 has a higher weight, then we want it to come - // first. - return result2.camelCaseWeight - result1.camelCaseWeight; - } - return 0; - } function createSegment(text) { return { totalTextChunk: createTextChunk(text), @@ -39902,7 +40806,7 @@ var ts; if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { return false; } - // TODO: find a way to determine this for any unicode characters in a + // TODO: find a way to determine this for any unicode characters in a // non-allocating manner. var str = String.fromCharCode(ch); return str === str.toUpperCase(); @@ -39915,19 +40819,11 @@ var ts; if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { return false; } - // TODO: find a way to determine this for any unicode characters in a + // TODO: find a way to determine this for any unicode characters in a // non-allocating manner. var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function containsUpperCaseLetter(string) { - for (var i = 0, n = string.length; i < n; i++) { - if (isUpperCaseLetter(string.charCodeAt(i))) { - return true; - } - } - return false; - } function startsWith(string, search) { for (var i = 0, n = search.length; i < n; i++) { if (string.charCodeAt(i) !== search.charCodeAt(i)) { @@ -39964,7 +40860,7 @@ var ts; if (ch < 127 /* maxAsciiCharacter */) { return ch; } - // TODO: find a way to compute this for any unicode characters in a + // TODO: find a way to compute this for any unicode characters in a // non-allocating manner. return String.fromCharCode(ch).toLowerCase().charCodeAt(0); } @@ -39982,9 +40878,10 @@ var ts; for (var i = 0; i < pattern.length; i++) { var ch = pattern.charCodeAt(i); if (isWordChar(ch)) { - if (wordLength++ === 0) { + if (wordLength === 0) { wordStart = i; } + wordLength++; } else { if (wordLength > 0) { @@ -40115,7 +41012,7 @@ var ts; var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); // See if the casing indicates we're starting a new word. Note: if we're breaking on // words, then just seeing an upper case character isn't enough. Instead, it has to - // be uppercase and the previous character can't be uppercase. + // be uppercase and the previous character can't be uppercase. // // For example, breaking "AddMetadata" on words would make: Add Metadata // @@ -40305,7 +41202,7 @@ var ts; } return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo); function createJavaScriptSignatureHelpItems(argumentInfo) { - if (argumentInfo.invocation.kind !== 168 /* CallExpression */) { + if (argumentInfo.invocation.kind !== 170 /* CallExpression */) { return undefined; } // See if we can find some symbol with the call expression name that has call signatures. @@ -40313,7 +41210,7 @@ var ts; var expression = callExpression.expression; var name = expression.kind === 69 /* Identifier */ ? expression - : expression.kind === 166 /* PropertyAccessExpression */ + : expression.kind === 168 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.text) { @@ -40346,7 +41243,7 @@ var ts; * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node) { - if (node.parent.kind === 168 /* CallExpression */ || node.parent.kind === 169 /* NewExpression */) { + if (node.parent.kind === 170 /* CallExpression */ || node.parent.kind === 171 /* NewExpression */) { var callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a sig help session @@ -40399,25 +41296,25 @@ var ts; }; } } - else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 172 /* TaggedTemplateExpression */) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0); } } - else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 172 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 185 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } - else if (node.parent.kind === 190 /* TemplateSpan */ && node.parent.parent.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.parent.kind === 192 /* TemplateSpan */ && node.parent.parent.parent.kind === 172 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 185 /* TemplateExpression */); // If we're just after a template tail, don't show signature help. if (node.kind === 14 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; @@ -40535,7 +41432,7 @@ var ts; // // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 183 /* TemplateExpression */) { + if (template.kind === 185 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -40544,7 +41441,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node) { - for (var n = node; n.kind !== 248 /* SourceFile */; n = n.parent) { + for (var n = node; n.kind !== 250 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -40744,25 +41641,25 @@ var ts; return false; } switch (n.kind) { - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 165 /* ObjectLiteralExpression */: - case 161 /* ObjectBindingPattern */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: + case 167 /* ObjectLiteralExpression */: + case 163 /* ObjectBindingPattern */: case 155 /* TypeLiteral */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 220 /* CaseBlock */: + case 194 /* Block */: + case 221 /* ModuleBlock */: + case 222 /* CaseBlock */: return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 169 /* NewExpression */: + case 171 /* NewExpression */: if (!n.arguments) { return true; } // fall through - case 168 /* CallExpression */: - case 172 /* ParenthesizedExpression */: + case 170 /* CallExpression */: + case 174 /* ParenthesizedExpression */: case 160 /* ParenthesizedType */: return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); case 152 /* FunctionType */: @@ -40771,13 +41668,13 @@ var ts; case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 148 /* ConstructSignature */: case 147 /* CallSignature */: - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -40787,19 +41684,19 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 18 /* CloseParenToken */, sourceFile); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 196 /* IfStatement */: + case 198 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 195 /* ExpressionStatement */: + case 197 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 23 /* SemicolonToken */); - case 164 /* ArrayLiteralExpression */: - case 162 /* ArrayBindingPattern */: - case 167 /* ElementAccessExpression */: + case 166 /* ArrayLiteralExpression */: + case 164 /* ArrayBindingPattern */: + case 169 /* ElementAccessExpression */: case 136 /* ComputedPropertyName */: case 157 /* TupleType */: return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); @@ -40808,16 +41705,16 @@ var ts; return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicitly always consider them non-completed return false; - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 200 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 197 /* DoStatement */: + case 199 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; var hasWhileKeyword = findChildOfKind(n, 104 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { @@ -40826,25 +41723,25 @@ var ts; return isCompletedNode(n.statement, sourceFile); case 154 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 176 /* TypeOfExpression */: - case 175 /* DeleteExpression */: - case 177 /* VoidExpression */: - case 184 /* YieldExpression */: - case 185 /* SpreadElementExpression */: + case 178 /* TypeOfExpression */: + case 177 /* DeleteExpression */: + case 179 /* VoidExpression */: + case 186 /* YieldExpression */: + case 187 /* SpreadElementExpression */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 170 /* TaggedTemplateExpression */: + case 172 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 183 /* TemplateExpression */: + case 185 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 190 /* TemplateSpan */: + case 192 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -40900,7 +41797,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 === 271 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 273 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -41006,7 +41903,7 @@ var ts; function findPrecedingToken(position, sourceFile, startNode) { return find(startNode || sourceFile); function findRightmostToken(n) { - if (isToken(n) || n.kind === 236 /* JsxText */) { + if (isToken(n) || n.kind === 238 /* JsxText */) { return n; } var children = n.getChildren(); @@ -41014,7 +41911,7 @@ var ts; return candidate && findRightmostToken(candidate); } function find(n) { - if (isToken(n) || n.kind === 236 /* JsxText */) { + if (isToken(n) || n.kind === 238 /* JsxText */) { return n; } var children = n.getChildren(); @@ -41028,10 +41925,10 @@ var ts; // if no - position is in the node itself so we should recurse in it. // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). // if this is the case - then we should assume that token in question is located in previous child. - if (position < child.end && (nodeHasTokens(child) || child.kind === 236 /* JsxText */)) { + if (position < child.end && (nodeHasTokens(child) || child.kind === 238 /* JsxText */)) { var start = child.getStart(sourceFile); var lookInPreviousChild = (start >= position) || - (child.kind === 236 /* JsxText */ && start === child.end); // whitespace only JsxText + (child.kind === 238 /* JsxText */ && start === child.end); // whitespace only JsxText if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); @@ -41043,8 +41940,8 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 248 /* SourceFile */); - // Here we know that none of child token nodes embrace the position, + ts.Debug.assert(startNode !== undefined || n.kind === 250 /* SourceFile */); + // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' @@ -41065,7 +41962,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); - return token && token.kind === 9 /* StringLiteral */ && position > token.getStart(); + return token && (token.kind === 9 /* StringLiteral */ || token.kind === 162 /* StringLiteralType */) && position > token.getStart(); } ts.isInString = isInString; function isInComment(sourceFile, position) { @@ -41169,10 +42066,10 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 151 /* TypeReference */ || node.kind === 168 /* CallExpression */) { + if (node.kind === 151 /* TypeReference */ || node.kind === 170 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 214 /* ClassDeclaration */ || node.kind === 215 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 216 /* ClassDeclaration */ || node.kind === 217 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -41195,6 +42092,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 /* StringLiteral */ + || kind === 162 /* StringLiteralType */ || kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; @@ -41431,7 +42329,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 226 /* ImportSpecifier */ || location.parent.kind === 230 /* ExportSpecifier */) && + (location.parent.kind === 228 /* ImportSpecifier */ || location.parent.kind === 232 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -41488,6 +42386,7 @@ var ts; advance: advance, readTokenInfo: readTokenInfo, isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, close: function () { ts.Debug.assert(scanner !== undefined); @@ -41553,10 +42452,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 238 /* JsxAttribute */: - case 235 /* JsxOpeningElement */: - case 237 /* JsxClosingElement */: - case 234 /* JsxSelfClosingElement */: + case 240 /* JsxAttribute */: + case 237 /* JsxOpeningElement */: + case 239 /* JsxClosingElement */: + case 236 /* JsxSelfClosingElement */: return node.kind === 69 /* Identifier */; } } @@ -41763,7 +42662,7 @@ var ts; return false; }; return FormattingContext; - })(); + }()); formatting.FormattingContext = FormattingContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41802,7 +42701,7 @@ var ts; "flag=" + this.Flag + "]"; }; return Rule; - })(); + }()); formatting.Rule = Rule; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41849,7 +42748,7 @@ var ts; return new RuleDescriptor(left, right); }; return RuleDescriptor; - })(); + }()); formatting.RuleDescriptor = RuleDescriptor; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41891,7 +42790,7 @@ var ts; return result; }; return RuleOperation; - })(); + }()); formatting.RuleOperation = RuleOperation; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41926,7 +42825,7 @@ var ts; }; RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; - })(); + }()); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42030,6 +42929,7 @@ var ts; // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9 /* StringLiteral */, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); // Lambda expressions + this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 34 /* EqualsGreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // Optional parameters and let args this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22 /* DotDotDotToken */, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); @@ -42055,72 +42955,68 @@ var ts; this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // template string - this.SpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - 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.IsSameLineTokenContext), 8 /* Delete */)); + 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.IsSameLineTokenContext), 8 /* Delete */)); // These rules are higher in priority than user-configurable rules. - this.HighPriorityCommonRules = - [ - this.IgnoreBeforeComment, this.IgnoreAfterLineComment, - this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, - this.NoSpaceAfterQuestionMark, - this.NoSpaceBeforeDot, this.NoSpaceAfterDot, - this.NoSpaceAfterUnaryPrefixOperator, - this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, - this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, - this.SpaceAfterPostincrementWhenFollowedByAdd, - this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, - this.SpaceAfterPostdecrementWhenFollowedBySubtract, - this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, - this.NoSpaceAfterCloseBrace, - this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, - this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, - this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, - this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, - this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, - this.NoSpaceBetweenReturnAndSemicolon, - this.SpaceAfterCertainKeywords, - this.SpaceAfterLetConstInVariableDeclaration, - this.NoSpaceBeforeOpenParenInFuncCall, - this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, - this.SpaceAfterVoidOperator, - this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, - this.SpaceBetweenTagAndTemplateString, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, - // TypeScript-specific rules - this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, - this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, - this.SpaceAfterModuleName, - this.SpaceAfterArrow, - this.NoSpaceAfterEllipsis, - this.NoSpaceAfterOptionalParameters, - this.NoSpaceBetweenEmptyInterfaceBraceBrackets, - this.NoSpaceBeforeOpenAngularBracket, - this.NoSpaceBetweenCloseParenAndAngularBracket, - this.NoSpaceAfterOpenAngularBracket, - this.NoSpaceBeforeCloseAngularBracket, - this.NoSpaceAfterCloseAngularBracket, - this.NoSpaceAfterTypeAssertion, - this.SpaceBeforeAt, - this.NoSpaceAfterAt, - this.SpaceAfterDecorator, - ]; + this.HighPriorityCommonRules = [ + this.IgnoreBeforeComment, this.IgnoreAfterLineComment, + this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, + this.NoSpaceAfterQuestionMark, + this.NoSpaceBeforeDot, this.NoSpaceAfterDot, + this.NoSpaceAfterUnaryPrefixOperator, + this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, + this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, + this.SpaceAfterPostincrementWhenFollowedByAdd, + this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, + this.SpaceAfterPostdecrementWhenFollowedBySubtract, + this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, + this.NoSpaceAfterCloseBrace, + this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, + this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, + this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, + this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, + this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, + this.NoSpaceBetweenReturnAndSemicolon, + this.SpaceAfterCertainKeywords, + this.SpaceAfterLetConstInVariableDeclaration, + this.NoSpaceBeforeOpenParenInFuncCall, + this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, + this.SpaceAfterVoidOperator, + this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, + this.NoSpaceBetweenTagAndTemplateString, + // TypeScript-specific rules + this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, + this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, + this.SpaceAfterModuleName, + this.SpaceBeforeArrow, this.SpaceAfterArrow, + this.NoSpaceAfterEllipsis, + this.NoSpaceAfterOptionalParameters, + this.NoSpaceBetweenEmptyInterfaceBraceBrackets, + this.NoSpaceBeforeOpenAngularBracket, + this.NoSpaceBetweenCloseParenAndAngularBracket, + this.NoSpaceAfterOpenAngularBracket, + this.NoSpaceBeforeCloseAngularBracket, + this.NoSpaceAfterCloseAngularBracket, + this.NoSpaceAfterTypeAssertion, + this.SpaceBeforeAt, + this.NoSpaceAfterAt, + this.SpaceAfterDecorator, + ]; // These rules are lower in priority than user-configurable rules. - this.LowPriorityCommonRules = - [ - this.NoSpaceBeforeSemicolon, - this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, - this.NoSpaceBeforeComma, - this.NoSpaceBeforeOpenBracket, - this.NoSpaceAfterCloseBracket, - this.SpaceAfterSemicolon, - this.NoSpaceBeforeOpenParenInFuncDecl, - this.SpaceBetweenStatements, this.SpaceAfterTryFinally - ]; + this.LowPriorityCommonRules = [ + this.NoSpaceBeforeSemicolon, + this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, + this.NoSpaceBeforeComma, + this.NoSpaceBeforeOpenBracket, + this.NoSpaceAfterCloseBracket, + this.SpaceAfterSemicolon, + this.NoSpaceBeforeOpenParenInFuncDecl, + this.SpaceBetweenStatements, this.SpaceAfterTryFinally + ]; /// /// 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.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, 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.IsSameLineTokenContext), 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.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); @@ -42152,15 +43048,20 @@ var ts; this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenBracketToken */, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // Insert space after opening and before closing template string braces + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + 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.IsSameLineTokenContext), 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.IsSameLineTokenContext), 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 */)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_34 in o) { - if (o[name_34] === rule) { - return name_34; + for (var name_30 in o) { + if (o[name_30] === rule) { + return name_30; } } throw new Error("Unknown rule"); @@ -42169,39 +43070,39 @@ var ts; /// Contexts /// Rules.IsForContext = function (context) { - return context.contextNode.kind === 199 /* ForStatement */; + return context.contextNode.kind === 201 /* ForStatement */; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 189 /* AsExpression */: + case 183 /* BinaryExpression */: + case 184 /* ConditionalExpression */: + case 191 /* AsExpression */: case 150 /* TypePredicate */: case 158 /* UnionType */: case 159 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 163 /* BindingElement */: + case 165 /* BindingElement */: // equals in type X = ... - case 216 /* TypeAliasDeclaration */: + case 218 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: // equal in p = 0; case 138 /* Parameter */: - case 247 /* EnumMember */: + case 249 /* EnumMember */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return context.currentTokenSpan.kind === 56 /* EqualsToken */ || context.nextTokenSpan.kind === 56 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 200 /* ForInStatement */: + case 202 /* ForInStatement */: return context.currentTokenSpan.kind === 90 /* InKeyword */ || context.nextTokenSpan.kind === 90 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 201 /* ForOfStatement */: + case 203 /* ForOfStatement */: return context.currentTokenSpan.kind === 134 /* OfKeyword */ || context.nextTokenSpan.kind === 134 /* OfKeyword */; } return false; @@ -42210,7 +43111,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 182 /* ConditionalExpression */; + return context.contextNode.kind === 184 /* ConditionalExpression */; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. @@ -42254,17 +43155,17 @@ var ts; return true; } switch (node.kind) { - case 192 /* Block */: - case 220 /* CaseBlock */: - case 165 /* ObjectLiteralExpression */: - case 219 /* ModuleBlock */: + case 194 /* Block */: + case 222 /* CaseBlock */: + case 167 /* ObjectLiteralExpression */: + case 221 /* ModuleBlock */: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: //case SyntaxKind.MemberFunctionDeclaration: @@ -42272,75 +43173,75 @@ var ts; case 146 /* SetAccessor */: ///case SyntaxKind.MethodSignature: case 147 /* CallSignature */: - case 173 /* FunctionExpression */: + case 175 /* FunctionExpression */: case 144 /* Constructor */: - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: //case SyntaxKind.ConstructorDeclaration: //case SyntaxKind.SimpleArrowFunctionExpression: //case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return true; } return false; }; Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 213 /* FunctionDeclaration */ || context.contextNode.kind === 173 /* FunctionExpression */; + return context.contextNode.kind === 215 /* FunctionDeclaration */ || context.contextNode.kind === 175 /* FunctionExpression */; }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: case 155 /* TypeLiteral */: - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 214 /* ClassDeclaration */: - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: - case 192 /* Block */: - case 244 /* CatchClause */: - case 219 /* ModuleBlock */: - case 206 /* SwitchStatement */: + case 216 /* ClassDeclaration */: + case 220 /* ModuleDeclaration */: + case 219 /* EnumDeclaration */: + case 194 /* Block */: + case 246 /* CatchClause */: + case 221 /* ModuleBlock */: + case 208 /* SwitchStatement */: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 196 /* IfStatement */: - case 206 /* SwitchStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: - case 209 /* TryStatement */: - case 197 /* DoStatement */: - case 205 /* WithStatement */: + case 198 /* IfStatement */: + case 208 /* SwitchStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 200 /* WhileStatement */: + case 211 /* TryStatement */: + case 199 /* DoStatement */: + case 207 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 244 /* CatchClause */: + case 246 /* CatchClause */: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 165 /* ObjectLiteralExpression */; + return context.contextNode.kind === 167 /* ObjectLiteralExpression */; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 168 /* CallExpression */; + return context.contextNode.kind === 170 /* CallExpression */; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 169 /* NewExpression */; + return context.contextNode.kind === 171 /* NewExpression */; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); @@ -42348,8 +43249,11 @@ var ts; Rules.IsPreviousTokenNotComma = function (context) { return context.currentTokenSpan.kind !== 24 /* CommaToken */; }; + Rules.IsNextTokenNotCloseBracket = function (context) { + return context.nextTokenSpan.kind !== 20 /* CloseBracketToken */; + }; Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 174 /* ArrowFunction */; + return context.contextNode.kind === 176 /* ArrowFunction */; }; Rules.IsSameLineTokenContext = function (context) { return context.TokensAreOnSameLine(); @@ -42370,14 +43274,14 @@ var ts; return node.kind === 139 /* Decorator */; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 212 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 214 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 218 /* ModuleDeclaration */; + return context.contextNode.kind === 220 /* ModuleDeclaration */; }; Rules.IsObjectTypeContext = function (context) { return context.contextNode.kind === 155 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; @@ -42388,20 +43292,20 @@ var ts; } switch (parent.kind) { case 151 /* TypeReference */: - case 171 /* TypeAssertionExpression */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 173 /* TypeAssertionExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 217 /* InterfaceDeclaration */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 147 /* CallSignature */: case 148 /* ConstructSignature */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 188 /* ExpressionWithTypeArguments */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: + case 190 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -42412,16 +43316,16 @@ var ts; Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 171 /* TypeAssertionExpression */; + return context.contextNode.kind === 173 /* TypeAssertionExpression */; }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 177 /* VoidExpression */; + return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 179 /* VoidExpression */; }; Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 184 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 186 /* YieldExpression */ && context.contextNode.expression !== undefined; }; return Rules; - })(); + }()); formatting.Rules = Rules; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42489,7 +43393,7 @@ var ts; return null; }; return RulesMap; - })(); + }()); formatting.RulesMap = RulesMap; var MaskBitSize = 5; var Mask = 0x1f; @@ -42541,7 +43445,7 @@ var ts; this.rulesInsertionIndexBitmap = temp; }; return RulesBucketConstructionState; - })(); + }()); formatting.RulesBucketConstructionState = RulesBucketConstructionState; var RulesBucket = (function () { function RulesBucket() { @@ -42576,7 +43480,7 @@ var ts; state.IncreaseInsertionIndex(position); }; return RulesBucket; - })(); + }()); formatting.RulesBucket = RulesBucket; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42604,7 +43508,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenRangeAccess; - })(); + }()); Shared.TokenRangeAccess = TokenRangeAccess; var TokenValuesAccess = (function () { function TokenValuesAccess(tks) { @@ -42617,7 +43521,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenValuesAccess; - })(); + }()); Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { @@ -42630,7 +43534,7 @@ var ts; return tokenValue === this.token; }; return TokenSingleValueAccess; - })(); + }()); Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { @@ -42649,7 +43553,7 @@ var ts; return "[allTokens]"; }; return TokenAllAccess; - })(); + }()); Shared.TokenAllAccess = TokenAllAccess; var TokenRange = (function () { function TokenRange(tokenAccess) { @@ -42691,7 +43595,7 @@ var ts; TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 128 /* NumberKeyword */, 130 /* StringKeyword */, 120 /* BooleanKeyword */, 131 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); return TokenRange; - })(); + }()); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -42777,6 +43681,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } + if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); + } + else { + rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); + } if (options.InsertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } @@ -42802,7 +43714,7 @@ var ts; return rules; }; return RulesProvider; - })(); + }()); formatting.RulesProvider = RulesProvider; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42903,17 +43815,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 192 /* Block */ && ts.rangeContainsRange(body.statements, node); - case 248 /* SourceFile */: - case 192 /* Block */: - case 219 /* ModuleBlock */: + return body && body.kind === 194 /* Block */ && ts.rangeContainsRange(body.statements, node); + case 250 /* SourceFile */: + case 194 /* Block */: + case 221 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -43011,17 +43923,17 @@ var ts; */ function getOwnOrInheritedDelta(n, options, sourceFile) { var previousLine = -1 /* Unknown */; - var childKind = 0 /* Unknown */; + var child; while (n) { var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; if (previousLine !== -1 /* Unknown */ && line !== previousLine) { break; } - if (formatting.SmartIndenter.shouldIndentChildNode(n.kind, childKind)) { + if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { return options.IndentSize; } previousLine = line; - childKind = n.kind; + child = n; n = n.parent; } return 0; @@ -43051,6 +43963,13 @@ var ts; var delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile); processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } + if (!formattingScanner.isOnToken()) { + var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (leadingTrivia) { + processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined); + trimTrailingWhitespacesForRemainingRange(); + } + } formattingScanner.close(); return edits; // local functions @@ -43062,7 +43981,8 @@ var ts; * to inherited indentation from its predecessors. */ function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { - if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos)) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || + ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { if (inheritedIndentation !== -1 /* Unknown */) { return inheritedIndentation; } @@ -43079,32 +43999,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - if (indentation === -1 /* Unknown */) { - if (isSomeBlock(node.kind)) { - // blocks should be indented in - // - other blocks - // - source file - // - switch\default clauses - if (isSomeBlock(parent.kind) || - parent.kind === 248 /* SourceFile */ || - parent.kind === 241 /* CaseClause */ || - parent.kind === 242 /* DefaultClause */) { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - else { - indentation = parentDynamicIndentation.getIndentation(); - } - } - else { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); - } - else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - } - } - var delta = formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -43112,7 +44007,15 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + } + else if (indentation === -1 /* Unknown */) { + if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + indentation = parentDynamicIndentation.getIndentation(); + } + else { + indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + } } return { indentation: indentation, @@ -43124,10 +44027,10 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 214 /* ClassDeclaration */: return 73 /* ClassKeyword */; - case 215 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; - case 213 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; - case 217 /* EnumDeclaration */: return 217 /* EnumDeclaration */; + case 216 /* ClassDeclaration */: return 73 /* ClassKeyword */; + case 217 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; + case 215 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; + case 219 /* EnumDeclaration */: return 219 /* EnumDeclaration */; case 145 /* GetAccessor */: return 123 /* GetKeyword */; case 146 /* SetAccessor */: return 129 /* SetKeyword */; case 143 /* MethodDeclaration */: @@ -43142,7 +44045,7 @@ var ts; } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { return { - getIndentationForComment: function (kind, tokenIndentation) { + getIndentationForComment: function (kind, tokenIndentation, container) { switch (kind) { // preceding comment to the token that closes the indentation scope inherits the indentation from the scope // .. { @@ -43151,11 +44054,11 @@ var ts; case 16 /* CloseBraceToken */: case 20 /* CloseBracketToken */: case 18 /* CloseParenToken */: - return indentation + delta; + return indentation + getEffectiveDelta(delta, container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, - getIndentationForToken: function (line, kind) { + getIndentationForToken: function (line, kind, container) { if (nodeStartLine !== line && node.decorators) { if (kind === getFirstNonDecoratorTokenOfNode(node)) { // if this token is the first token following the list of decorators, we do not need to indent @@ -43176,20 +44079,20 @@ var ts; return indentation; default: // if token line equals to the line of containing node (this is a first token in the node) - use node indentation - return nodeStartLine !== line ? indentation + delta : indentation; + return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; } }, getIndentation: function () { return indentation; }, - getDelta: function () { return delta; }, + getDelta: function (child) { return getEffectiveDelta(delta, child); }, recomputeIndentation: function (lineAdded) { - if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { indentation += options.IndentSize; } else { indentation -= options.IndentSize; } - if (formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */)) { + if (formatting.SmartIndenter.shouldIndentChildNode(node)) { delta = options.IndentSize; } else { @@ -43198,6 +44101,10 @@ var ts; } } }; + function getEffectiveDelta(delta, child) { + // Delta value should be zero when the node explicitly prevents indentation of the child node + return formatting.SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0; + } } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { @@ -43269,7 +44176,7 @@ var ts; // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules var tokenInfo = formattingScanner.readTokenInfo(child); ts.Debug.assert(tokenInfo.token.end === child.end); - consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } var effectiveParentStartLine = child.kind === 139 /* Decorator */ ? childStartLine : undecoratedParentStartLine; @@ -43323,7 +44230,7 @@ var ts; } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation) { + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; @@ -43358,10 +44265,10 @@ var ts; } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : -1 /* Unknown */; if (currentTokenInfo.leadingTrivia) { - var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation); + var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); var indentNextTokenOrTrivia = true; for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { var triviaItem = _a[_i]; @@ -43450,9 +44357,7 @@ var ts; } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line - trimTrailingWhitespaces = - (rule.Operation.Action & (4 /* NewLine */ | 2 /* Space */)) && - rule.Flag !== 1 /* CanDeleteNewLines */; + trimTrailingWhitespaces = !(rule.Operation.Action & 8 /* Delete */) && rule.Flag !== 1 /* CanDeleteNewLines */; } else { trimTrailingWhitespaces = true; @@ -43535,16 +44440,36 @@ var ts; if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { continue; } - var pos = lineEndPosition; - while (pos >= lineStartPosition && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { - pos--; - } - if (pos !== lineEndPosition) { - ts.Debug.assert(pos === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))); - recordDelete(pos + 1, lineEndPosition - pos); + var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + if (whitespaceStart !== -1) { + ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(whitespaceStart - 1))); + recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); } } } + /** + * @param start The position of the first character in range + * @param end The position of the last character in range + */ + function getTrailingWhitespaceStartPosition(start, end) { + var pos = end; + while (pos >= start && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== end) { + return pos + 1; + } + return -1; + } + /** + * Trimming will be done for lines after the previous range + */ + function trimTrailingWhitespacesForRemainingRange() { + var startPosition = previousRange ? previousRange.end : originalRange.pos; + var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); + } function newTextChange(start, len, newText) { return { span: ts.createTextSpan(start, len), newText: newText }; } @@ -43598,8 +44523,8 @@ var ts; } function isSomeBlock(kind) { switch (kind) { - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 194 /* Block */: + case 221 /* ModuleBlock */: return true; } return false; @@ -43607,11 +44532,11 @@ var ts; function getOpenTokenForList(node, list) { switch (node.kind) { case 144 /* Constructor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: if (node.typeParameters === list) { return 25 /* LessThanToken */; } @@ -43619,8 +44544,8 @@ var ts; return 17 /* OpenParenToken */; } break; - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: if (node.typeArguments === list) { return 25 /* LessThanToken */; } @@ -43744,7 +44669,7 @@ var ts; var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); } - if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 181 /* BinaryExpression */) { + if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 183 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -43758,7 +44683,7 @@ var ts; var currentStart; var indentationDelta; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current.kind, previous ? previous.kind : 0 /* Unknown */)) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) { currentStart = getStartLineAndCharacterForNode(current, sourceFile); if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) { indentationDelta = 0; @@ -43825,7 +44750,7 @@ var ts; } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line - if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) { + if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { indentationDelta += options.IndentSize; } current = parent; @@ -43863,7 +44788,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && - (parent.kind === 248 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 250 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -43896,7 +44821,7 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 196 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 198 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 80 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -43914,13 +44839,13 @@ var ts; return node.parent.typeArguments; } break; - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return node.parent.properties; - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return node.parent.elements; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 147 /* CallSignature */: @@ -43935,8 +44860,8 @@ var ts; } break; } - case 169 /* NewExpression */: - case 168 /* CallExpression */: { + case 171 /* NewExpression */: + case 170 /* CallExpression */: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -43966,8 +44891,8 @@ var ts; if (node.kind === 18 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 168 /* CallExpression */ || - node.parent.kind === 169 /* NewExpression */) && + if (node.parent && (node.parent.kind === 170 /* CallExpression */ || + node.parent.kind === 171 /* NewExpression */) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); @@ -43985,10 +44910,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: + case 168 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: node = node.expression; break; default: @@ -44052,34 +44977,35 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 195 /* ExpressionStatement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 164 /* ArrayLiteralExpression */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 165 /* ObjectLiteralExpression */: + case 197 /* ExpressionStatement */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 166 /* ArrayLiteralExpression */: + case 194 /* Block */: + case 221 /* ModuleBlock */: + case 167 /* ObjectLiteralExpression */: case 155 /* TypeLiteral */: case 157 /* TupleType */: - case 220 /* CaseBlock */: - case 242 /* DefaultClause */: - case 241 /* CaseClause */: - case 172 /* ParenthesizedExpression */: - case 166 /* PropertyAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 193 /* VariableStatement */: - case 211 /* VariableDeclaration */: - case 227 /* ExportAssignment */: - case 204 /* ReturnStatement */: - case 182 /* ConditionalExpression */: - case 162 /* ArrayBindingPattern */: - case 161 /* ObjectBindingPattern */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: + case 222 /* CaseBlock */: + case 244 /* DefaultClause */: + case 243 /* CaseClause */: + case 174 /* ParenthesizedExpression */: + case 168 /* PropertyAccessExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: + case 195 /* VariableStatement */: + case 213 /* VariableDeclaration */: + case 229 /* ExportAssignment */: + case 206 /* ReturnStatement */: + case 184 /* ConditionalExpression */: + case 164 /* ArrayBindingPattern */: + case 163 /* ObjectBindingPattern */: + case 237 /* JsxOpeningElement */: + case 236 /* JsxSelfClosingElement */: + case 242 /* JsxExpression */: case 142 /* MethodSignature */: case 147 /* CallSignature */: case 148 /* ConstructSignature */: @@ -44087,34 +45013,43 @@ var ts; case 152 /* FunctionType */: case 153 /* ConstructorType */: case 160 /* ParenthesizedType */: - case 170 /* TaggedTemplateExpression */: - case 178 /* AwaitExpression */: + case 172 /* TaggedTemplateExpression */: + case 180 /* AwaitExpression */: + case 227 /* NamedImports */: return true; } return false; } - function shouldIndentChildNode(parent, child) { - if (nodeContentIsAlwaysIndented(parent)) { - return true; - } - switch (parent) { - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 196 /* IfStatement */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + /* @internal */ + function nodeWillIndentChild(parent, child, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { + case 199 /* DoStatement */: + case 200 /* WhileStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 201 /* ForStatement */: + case 198 /* IfStatement */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 143 /* MethodDeclaration */: - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - return child !== 192 /* Block */; - default: - return false; + return childKind !== 194 /* Block */; + case 235 /* JsxElement */: + return childKind !== 239 /* JsxClosingElement */; } + // No explicit rule for given nodes so the result will follow the default value argument + return indentByDefault; + } + SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; + /* + Function returns true when the parent node should indent the given child by an explicit rule + */ + function shouldIndentChildNode(parent, child) { + return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); @@ -44157,7 +45092,7 @@ var ts; return undefined; }; return StringScriptSnapshot; - })(); + }()); function fromString(text) { return new StringScriptSnapshot(text); } @@ -44256,7 +45191,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(271 /* SyntaxList */, nodes.pos, nodes.end, 2048 /* Synthetic */, this); + var list = createNode(273 /* SyntaxList */, nodes.pos, nodes.end, 2048 /* Synthetic */, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -44333,7 +45268,7 @@ var ts; return child.kind < 135 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; return NodeObject; - })(); + }()); var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -44355,7 +45290,7 @@ var ts; return this.documentationComment; }; return SymbolObject; - })(); + }()); function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { var documentationComment = []; var docComments = getJsDocCommentsSeparatedByNewLines(); @@ -44373,7 +45308,7 @@ var ts; // Make sure we are collecting doc comment from declaration once, // In case of union property there might be same declaration multiple times // which only varies in type parameter - // Eg. let a: Array | Array; a.length + // Eg. const a: Array | Array; a.length // The property length will have two declarations of property length coming // from Array - Array and Array if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { @@ -44388,15 +45323,15 @@ var ts; }); } // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 218 /* ModuleDeclaration */ && declaration.body.kind === 218 /* ModuleDeclaration */) { + if (declaration.kind === 220 /* ModuleDeclaration */ && declaration.body.kind === 220 /* ModuleDeclaration */) { return; } // If this is dotted module name, get the doc comments from the parent - while (declaration.kind === 218 /* ModuleDeclaration */ && declaration.parent.kind === 218 /* ModuleDeclaration */) { + while (declaration.kind === 220 /* ModuleDeclaration */ && declaration.parent.kind === 220 /* ModuleDeclaration */) { declaration = declaration.parent; } // Get the cleaned js doc comment text from the declaration - ts.forEach(getJsDocCommentTextRange(declaration.kind === 211 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { + ts.forEach(getJsDocCommentTextRange(declaration.kind === 213 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedJsDocComment) { ts.addRange(jsDocCommentParts, cleanedJsDocComment); @@ -44444,7 +45379,8 @@ var ts; } function pushDocCommentLineText(docComments, text, blankLineCount) { // Add the empty lines in between texts - while (blankLineCount--) { + while (blankLineCount) { + blankLineCount--; docComments.push(ts.textPart("")); } docComments.push(ts.textPart(text)); @@ -44670,7 +45606,7 @@ var ts; : undefined; }; return TypeObject; - })(); + }()); var SignatureObject = (function () { function SignatureObject(checker) { this.checker = checker; @@ -44696,7 +45632,7 @@ var ts; return this.documentationComment; }; return SignatureObject; - })(); + }()); var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { @@ -44742,7 +45678,7 @@ var ts; } if (declaration.name.kind === 136 /* ComputedPropertyName */) { var expr = declaration.name.expression; - if (expr.kind === 166 /* PropertyAccessExpression */) { + if (expr.kind === 168 /* PropertyAccessExpression */) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -44762,7 +45698,7 @@ var ts; } function visit(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: var functionDeclaration = node; @@ -44784,31 +45720,31 @@ var ts; ts.forEachChild(node, visit); } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: - case 218 /* ModuleDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 230 /* ExportSpecifier */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 219 /* EnumDeclaration */: + case 220 /* ModuleDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 232 /* ExportSpecifier */: + case 228 /* ImportSpecifier */: + case 223 /* ImportEqualsDeclaration */: + case 225 /* ImportClause */: + case 226 /* NamespaceImport */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 155 /* TypeLiteral */: addDeclaration(node); // fall through case 144 /* Constructor */: - case 193 /* VariableStatement */: - case 212 /* VariableDeclarationList */: - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 219 /* ModuleBlock */: + case 195 /* VariableStatement */: + case 214 /* VariableDeclarationList */: + case 163 /* ObjectBindingPattern */: + case 164 /* ArrayBindingPattern */: + case 221 /* ModuleBlock */: ts.forEachChild(node, visit); break; - case 192 /* Block */: + case 194 /* Block */: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } @@ -44819,25 +45755,25 @@ var ts; break; } // fall through - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); break; } - case 247 /* EnumMember */: + case 249 /* EnumMember */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: addDeclaration(node); break; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -44849,7 +45785,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 226 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -44862,12 +45798,12 @@ var ts; } }; return SourceFileObject; - })(NodeObject); + }(NodeObject)); var TextChange = (function () { function TextChange() { } return TextChange; - })(); + }()); ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { @@ -44957,7 +45893,7 @@ var ts; // enum E ScriptElementKind.enumElement = "enum"; // Inside module and script only - // let v = .. + // const v = .. ScriptElementKind.variableElement = "var"; // Inside function ScriptElementKind.localVariableElement = "local var"; @@ -45026,7 +45962,7 @@ var ts; ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; return ClassificationTypeNames; - })(); + }()); ts.ClassificationTypeNames = ClassificationTypeNames; (function (ClassificationType) { ClassificationType[ClassificationType["comment"] = 1] = "comment"; @@ -45065,16 +46001,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 173 /* FunctionExpression */) { + if (declaration.kind === 175 /* FunctionExpression */) { return true; } - if (declaration.kind !== 211 /* VariableDeclaration */ && declaration.kind !== 213 /* FunctionDeclaration */) { + if (declaration.kind !== 213 /* VariableDeclaration */ && declaration.kind !== 215 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent_8 = declaration.parent; !ts.isFunctionBlock(parent_8); parent_8 = parent_8.parent) { // Reached source file or module block - if (parent_8.kind === 248 /* SourceFile */ || parent_8.kind === 219 /* ModuleBlock */) { + if (parent_8.kind === 250 /* SourceFile */ || parent_8.kind === 221 /* ModuleBlock */) { return false; } } @@ -45157,7 +46093,7 @@ var ts; return file && file.scriptSnapshot; }; return HostCache; - })(); + }()); var SyntaxTreeCache = (function () { function SyntaxTreeCache(host) { this.host = host; @@ -45172,7 +46108,7 @@ var ts; var sourceFile; if (this.currentFileName !== fileName) { // This is a new file, just parse it - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents:*/ true); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents*/ true); } else if (this.currentFileVersion !== version) { // This is the same file, just a newer version. Incrementally parse the file. @@ -45189,7 +46125,7 @@ var ts; return this.currentSourceFile; }; return SyntaxTreeCache; - })(); + }()); function setSourceFileFields(sourceFile, scriptSnapshot, version) { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; @@ -45234,7 +46170,7 @@ var ts; sourceMapText = text; } else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name); + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); outputText = text; } }, @@ -45244,7 +46180,8 @@ var ts; getCurrentDirectory: function () { return ""; }, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; } + readFile: function (fileName) { return ""; }, + directoryExists: function (directoryExists) { return true; } }; var program = ts.createProgram([inputFileName], options, compilerHost); var diagnostics; @@ -45326,7 +46263,7 @@ var ts; } } // Otherwise, just create a new source file. - return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents:*/ true); + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; function createGetCanonicalFileName(useCaseSensitivefileNames) { @@ -45342,7 +46279,7 @@ var ts; var buckets = {}; var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx; + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + +"|" + settings.allowJs; } function getBucketForCompilationSettings(settings, createIfMissing) { var key = getKeyFromCompilationSettings(settings); @@ -45353,7 +46290,7 @@ var ts; return bucket; } function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = ts.lookUp(buckets, name); var sourceFiles = []; entries.forEachValue(function (key, entry) { @@ -45369,13 +46306,13 @@ var ts; sourceFiles: sourceFiles }; }); - return JSON.stringify(bucketInfoArray, null, 2); + return JSON.stringify(bucketInfoArray, undefined, 2); } function acquireDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ true); + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring*/ true); } function updateDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ false); + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring*/ false); } function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); @@ -45384,7 +46321,7 @@ var ts; if (!entry) { ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents:*/ false); + var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false); entry = { sourceFile: sourceFile, languageServiceRefCount: 0, @@ -45411,7 +46348,7 @@ var ts; return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { - var bucket = getBucketForCompilationSettings(compilationSettings, false); + var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ false); ts.Debug.assert(bucket !== undefined); var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = bucket.get(path); @@ -45507,7 +46444,7 @@ var ts; } } else if (token === 56 /* EqualsToken */) { - if (tryConsumeRequireCall(/* skipCurrentToken */ true)) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } @@ -45599,7 +46536,7 @@ var ts; if (token === 69 /* Identifier */ || ts.isKeyword(token)) { token = scanner.scan(); if (token === 56 /* EqualsToken */) { - if (tryConsumeRequireCall(/* skipCurrentToken */ true)) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } @@ -45686,7 +46623,7 @@ var ts; if (tryConsumeDeclare() || tryConsumeImport() || tryConsumeExport() || - (detectJavaScriptImports && (tryConsumeRequireCall(/* skipCurrentToken */ false) || tryConsumeDefine()))) { + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { continue; } else { @@ -45705,7 +46642,7 @@ var ts; /// Helpers function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 207 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 209 /* LabeledStatement */ && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -45714,12 +46651,12 @@ var ts; } function isJumpStatementTarget(node) { return node.kind === 69 /* Identifier */ && - (node.parent.kind === 203 /* BreakStatement */ || node.parent.kind === 202 /* ContinueStatement */) && + (node.parent.kind === 205 /* BreakStatement */ || node.parent.kind === 204 /* ContinueStatement */) && node.parent.label === node; } function isLabelOfLabeledStatement(node) { return node.kind === 69 /* Identifier */ && - node.parent.kind === 207 /* LabeledStatement */ && + node.parent.kind === 209 /* LabeledStatement */ && node.parent.label === node; } /** @@ -45727,7 +46664,7 @@ var ts; * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 207 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 209 /* LabeledStatement */; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -45741,22 +46678,22 @@ var ts; return node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node; } function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 168 /* PropertyAccessExpression */ && node.parent.name === node; } function isCallExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 168 /* CallExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 170 /* CallExpression */ && node.parent.expression === node; } function isNewExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 169 /* NewExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 171 /* NewExpression */ && node.parent.expression === node; } function isNameOfModuleDeclaration(node) { - return node.parent.kind === 218 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 220 /* ModuleDeclaration */ && node.parent.name === node; } function isNameOfFunctionDeclaration(node) { return node.kind === 69 /* Identifier */ && @@ -45765,22 +46702,22 @@ var ts; /** Returns true if node is a name of an object literal property, e.g. "a" in x = { "a": 1 } */ function isNameOfPropertyAssignment(node) { return (node.kind === 69 /* Identifier */ || node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - (node.parent.kind === 245 /* PropertyAssignment */ || node.parent.kind === 246 /* ShorthandPropertyAssignment */) && node.parent.name === node; + (node.parent.kind === 247 /* PropertyAssignment */ || node.parent.kind === 248 /* ShorthandPropertyAssignment */) && node.parent.name === node; } function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { switch (node.parent.kind) { case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 247 /* EnumMember */: + case 247 /* PropertyAssignment */: + case 249 /* EnumMember */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return node.parent.name === node; - case 167 /* ElementAccessExpression */: + case 169 /* ElementAccessExpression */: return node.parent.argumentExpression === node; } } @@ -45854,17 +46791,17 @@ var ts; return undefined; } switch (node.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 218 /* ModuleDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: + case 220 /* ModuleDeclaration */: return node; } } @@ -45872,18 +46809,18 @@ var ts; ts.getContainerNode = getContainerNode; /* @internal */ function getNodeKind(node) { switch (node.kind) { - case 218 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; - case 214 /* ClassDeclaration */: return ScriptElementKind.classElement; - case 215 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; - case 216 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; - case 217 /* EnumDeclaration */: return ScriptElementKind.enumElement; - case 211 /* VariableDeclaration */: + case 220 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; + case 216 /* ClassDeclaration */: return ScriptElementKind.classElement; + case 217 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; + case 218 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; + case 219 /* EnumDeclaration */: return ScriptElementKind.enumElement; + case 213 /* VariableDeclaration */: return ts.isConst(node) ? ScriptElementKind.constElement : ts.isLet(node) ? ScriptElementKind.letElement : ScriptElementKind.variableElement; - case 213 /* FunctionDeclaration */: return ScriptElementKind.functionElement; + case 215 /* FunctionDeclaration */: return ScriptElementKind.functionElement; case 145 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; case 146 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; case 143 /* MethodDeclaration */: @@ -45897,13 +46834,13 @@ var ts; case 147 /* CallSignature */: return ScriptElementKind.callSignatureElement; case 144 /* Constructor */: return ScriptElementKind.constructorImplementationElement; case 137 /* TypeParameter */: return ScriptElementKind.typeParameterElement; - case 247 /* EnumMember */: return ScriptElementKind.variableElement; + case 249 /* EnumMember */: return ScriptElementKind.variableElement; case 138 /* Parameter */: return (node.flags & 56 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 223 /* ImportClause */: - case 230 /* ExportSpecifier */: - case 224 /* NamespaceImport */: + case 223 /* ImportEqualsDeclaration */: + case 228 /* ImportSpecifier */: + case 225 /* ImportClause */: + case 232 /* ExportSpecifier */: + case 226 /* NamespaceImport */: return ScriptElementKind.alias; } return ScriptElementKind.unknown; @@ -45922,7 +46859,7 @@ var ts; } }; return CancellationTokenObject; - })(); + }()); function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -45985,7 +46922,8 @@ var ts; (oldSettings.target !== newSettings.target || oldSettings.module !== newSettings.module || oldSettings.noResolve !== newSettings.noResolve || - oldSettings.jsx !== newSettings.jsx); + oldSettings.jsx !== newSettings.jsx || + oldSettings.allowJs !== newSettings.allowJs); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -46005,6 +46943,10 @@ var ts; // stub missing host functionality var entry = hostCache.getOrCreateEntry(fileName); return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + }, + directoryExists: function (directoryName) { + ts.Debug.assert(!host.resolveModuleNames); + return ts.directoryProbablyExists(directoryName, host); } }; if (host.resolveModuleNames) { @@ -46074,8 +47016,11 @@ var ts; return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); } function sourceFileUpToDate(sourceFile) { + if (!sourceFile) { + return false; + } var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); - return sourceFile && sourceFile.version === hostCache.getVersion(path); + return sourceFile.version === hostCache.getVersion(path); } function programUpToDate() { // If we haven't create a program yet, then it is not up-to-date @@ -46124,12 +47069,6 @@ var ts; function getSemanticDiagnostics(fileName) { synchronizeHostData(); var targetSourceFile = getValidSourceFile(fileName); - // For JavaScript files, we don't want to report the normal typescript semantic errors. - // Instead, we just report errors for using TypeScript-only constructs from within a - // JavaScript file. - if (ts.isSourceFileJavaScript(targetSourceFile)) { - return getJavaScriptSemanticDiagnostics(targetSourceFile); - } // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); @@ -46140,151 +47079,6 @@ var ts; var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return ts.concatenate(semanticDiagnostics, declarationDiagnostics); } - function getJavaScriptSemanticDiagnostics(sourceFile) { - var diagnostics = []; - walk(sourceFile); - return diagnostics; - function walk(node) { - if (!node) { - return false; - } - switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case 227 /* ExportAssignment */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; - case 214 /* ClassDeclaration */: - var classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case 243 /* HeritageClause */: - var heritageClause = node; - if (heritageClause.token === 106 /* ImplementsKeyword */) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 215 /* InterfaceDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 218 /* ModuleDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 216 /* TypeAliasDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: - case 213 /* FunctionDeclaration */: - var functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; - } - break; - case 193 /* VariableStatement */: - var variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; - case 211 /* VariableDeclaration */: - var variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; - } - break; - case 168 /* CallExpression */: - case 169 /* NewExpression */: - var expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - 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 138 /* Parameter */: - var parameter = node; - if (parameter.modifiers) { - 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) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, '?')); - return true; - } - if (parameter.type) { - diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 141 /* PropertyDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 217 /* EnumDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 171 /* TypeAssertionExpression */: - var typeAssertionExpression = node; - diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); - return true; - case 139 /* Decorator */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); - return true; - } - return ts.forEachChild(node, walk); - } - function checkTypeParameters(typeParameters) { - if (typeParameters) { - 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; - } - function checkTypeAnnotation(type) { - if (type) { - diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkModifiers(modifiers) { - if (modifiers) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 122 /* DeclareKeyword */: - diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - return true; - // These are all legal modifiers. - case 113 /* StaticKeyword */: - case 82 /* ExportKeyword */: - case 74 /* ConstKeyword */: - case 77 /* DefaultKeyword */: - case 115 /* AbstractKeyword */: - } - } - } - return false; - } - } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); @@ -46301,7 +47095,7 @@ var ts; // First check of the displayName is not external module; if it is an external module, it is not valid entry if ((symbol.flags & 1536 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { // If the symbol is external module, don't show it in the completion list - // (i.e declare module "http" { let x; } | // <= request completion here, "http" should not be there) + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } @@ -46324,20 +47118,14 @@ var ts; // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks) { - if (!ts.isIdentifierStart(name.charCodeAt(0), target)) { + if (!ts.isIdentifier(name, target)) { return undefined; } - for (var i = 1, n = name.length; i < n; i++) { - if (!ts.isIdentifierPart(name.charCodeAt(i), target)) { - return undefined; - } - } } return name; } function getCompletionData(fileName, position) { var typeChecker = program.getTypeChecker(); - var syntacticStart = new Date().getTime(); var sourceFile = getValidSourceFile(fileName); var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var isJsDocTagName = false; @@ -46349,7 +47137,7 @@ var ts; var insideComment = isInsideComment(sourceFile, currentToken, position); log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); if (insideComment) { - // The current position is next to the '@' sign, when no tag name being provided yet. + // The current position is next to the '@' sign, when no tag name being provided yet. // Provide a full list of tag names if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { isJsDocTagName = true; @@ -46364,9 +47152,9 @@ var ts; isJsDocTagName = true; } switch (tag.kind) { - case 269 /* JSDocTypeTag */: - case 267 /* JSDocParameterTag */: - case 268 /* JSDocReturnTag */: + case 271 /* JSDocTypeTag */: + case 269 /* JSDocParameterTag */: + case 270 /* JSDocReturnTag */: var tagWithExpression = tag; if (tagWithExpression.typeExpression) { insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; @@ -46378,7 +47166,7 @@ var ts; return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { - // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); return undefined; @@ -46393,9 +47181,9 @@ var ts; // 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_3 = new Date().getTime(); + var start_6 = new Date().getTime(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_3)); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_6)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -46413,7 +47201,7 @@ var ts; } var parent_9 = contextToken.parent, kind = contextToken.kind; if (kind === 21 /* DotToken */) { - if (parent_9.kind === 166 /* PropertyAccessExpression */) { + if (parent_9.kind === 168 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } @@ -46432,7 +47220,7 @@ var ts; isRightOfOpenTag = true; location = contextToken; } - else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 237 /* JsxClosingElement */) { + else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 239 /* JsxClosingElement */) { isStartingCloseTag = true; } } @@ -46475,7 +47263,7 @@ var ts; // Right of dot member completion list isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */) { + if (node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 168 /* PropertyAccessExpression */) { var symbol = typeChecker.getSymbolAtLocation(node); // This is an alias, follow what it aliases if (symbol && symbol.flags & 8388608 /* Alias */) { @@ -46531,7 +47319,7 @@ var ts; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType; - if ((jsxContainer.kind === 234 /* JsxSelfClosingElement */) || (jsxContainer.kind === 235 /* JsxOpeningElement */)) { + if ((jsxContainer.kind === 236 /* JsxSelfClosingElement */) || (jsxContainer.kind === 237 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { @@ -46603,15 +47391,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 236 /* JsxText */) { + if (contextToken.kind === 238 /* JsxText */) { return true; } if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 235 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 237 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 237 /* JsxClosingElement */ || contextToken.parent.kind === 234 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 233 /* JsxElement */; + if (contextToken.parent.kind === 239 /* JsxClosingElement */ || contextToken.parent.kind === 236 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 235 /* JsxElement */; } } return false; @@ -46621,36 +47409,36 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 24 /* CommaToken */: - return containingNodeKind === 168 /* CallExpression */ // func( a, | + return containingNodeKind === 170 /* CallExpression */ // func( a, | || containingNodeKind === 144 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 169 /* NewExpression */ // new C(a, | - || containingNodeKind === 164 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 181 /* BinaryExpression */ // let x = (a, | + || containingNodeKind === 171 /* NewExpression */ // new C(a, | + || containingNodeKind === 166 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 183 /* BinaryExpression */ // const x = (a, | || containingNodeKind === 152 /* FunctionType */; // var x: (s: string, list| case 17 /* OpenParenToken */: - return containingNodeKind === 168 /* CallExpression */ // func( | + return containingNodeKind === 170 /* CallExpression */ // func( | || containingNodeKind === 144 /* Constructor */ // constructor( | - || containingNodeKind === 169 /* NewExpression */ // new C(a| - || containingNodeKind === 172 /* ParenthesizedExpression */ // let x = (a| + || containingNodeKind === 171 /* NewExpression */ // new C(a| + || containingNodeKind === 174 /* ParenthesizedExpression */ // const x = (a| || containingNodeKind === 160 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 19 /* OpenBracketToken */: - return containingNodeKind === 164 /* ArrayLiteralExpression */ // [ | + return containingNodeKind === 166 /* ArrayLiteralExpression */ // [ | || containingNodeKind === 149 /* IndexSignature */ // [ | : string ] || containingNodeKind === 136 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 125 /* ModuleKeyword */: // module | case 126 /* NamespaceKeyword */: return true; case 21 /* DotToken */: - return containingNodeKind === 218 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 220 /* ModuleDeclaration */; // module A.| case 15 /* OpenBraceToken */: - return containingNodeKind === 214 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 216 /* ClassDeclaration */; // class A{ | case 56 /* EqualsToken */: - return containingNodeKind === 211 /* VariableDeclaration */ // let x = a| - || containingNodeKind === 181 /* BinaryExpression */; // x = a| + return containingNodeKind === 213 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 183 /* BinaryExpression */; // x = a| case 12 /* TemplateHead */: - return containingNodeKind === 183 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 185 /* TemplateExpression */; // `aa ${| case 13 /* TemplateMiddle */: - return containingNodeKind === 190 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 192 /* TemplateSpan */; // `aa ${10} dd ${| case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: @@ -46668,15 +47456,16 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 /* StringLiteral */ + || contextToken.kind === 162 /* StringLiteralType */ || contextToken.kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_4 = contextToken.getStart(); + var start_7 = 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_4 < position && position < end) { + if (start_7 < position && position < end) { return true; } if (position === end) { @@ -46697,14 +47486,14 @@ var ts; isMemberCompletion = true; var typeForObject; var existingMembers; - if (objectLikeContainer.kind === 165 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 167 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; typeForObject = typeChecker.getContextualType(objectLikeContainer); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 161 /* ObjectBindingPattern */) { + else if (objectLikeContainer.kind === 163 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -46750,9 +47539,9 @@ var ts; * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 225 /* NamedImports */ ? - 222 /* ImportDeclaration */ : - 228 /* ExportDeclaration */; + var declarationKind = namedImportsOrExports.kind === 227 /* NamedImports */ ? + 224 /* ImportDeclaration */ : + 230 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -46775,10 +47564,10 @@ var ts; function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // let x = { | + case 15 /* OpenBraceToken */: // const x = { | case 24 /* CommaToken */: var parent_10 = contextToken.parent; - if (parent_10 && (parent_10.kind === 165 /* ObjectLiteralExpression */ || parent_10.kind === 161 /* ObjectBindingPattern */)) { + if (parent_10 && (parent_10.kind === 167 /* ObjectLiteralExpression */ || parent_10.kind === 163 /* ObjectBindingPattern */)) { return parent_10; } break; @@ -46796,8 +47585,8 @@ var ts; case 15 /* OpenBraceToken */: // import { | case 24 /* CommaToken */: switch (contextToken.parent.kind) { - case 225 /* NamedImports */: - case 229 /* NamedExports */: + case 227 /* NamedImports */: + case 231 /* NamedExports */: return contextToken.parent; } } @@ -46811,12 +47600,12 @@ var ts; case 26 /* LessThanSlashToken */: case 39 /* SlashToken */: case 69 /* Identifier */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - if (parent_11 && (parent_11.kind === 234 /* JsxSelfClosingElement */ || parent_11.kind === 235 /* JsxOpeningElement */)) { + case 240 /* JsxAttribute */: + case 241 /* JsxSpreadAttribute */: + if (parent_11 && (parent_11.kind === 236 /* JsxSelfClosingElement */ || parent_11.kind === 237 /* JsxOpeningElement */)) { return parent_11; } - else if (parent_11.kind === 238 /* JsxAttribute */) { + else if (parent_11.kind === 240 /* JsxAttribute */) { return parent_11.parent; } break; @@ -46824,18 +47613,18 @@ var ts; // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 9 /* StringLiteral */: - if (parent_11 && ((parent_11.kind === 238 /* JsxAttribute */) || (parent_11.kind === 239 /* JsxSpreadAttribute */))) { + if (parent_11 && ((parent_11.kind === 240 /* JsxAttribute */) || (parent_11.kind === 241 /* JsxSpreadAttribute */))) { return parent_11.parent; } break; case 16 /* CloseBraceToken */: if (parent_11 && - parent_11.kind === 240 /* JsxExpression */ && + parent_11.kind === 242 /* JsxExpression */ && parent_11.parent && - (parent_11.parent.kind === 238 /* JsxAttribute */)) { + (parent_11.parent.kind === 240 /* JsxAttribute */)) { return parent_11.parent.parent; } - if (parent_11 && parent_11.kind === 239 /* JsxSpreadAttribute */) { + if (parent_11 && parent_11.kind === 241 /* JsxSpreadAttribute */) { return parent_11.parent; } break; @@ -46845,9 +47634,9 @@ var ts; } function isFunction(kind) { switch (kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 213 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: @@ -46866,54 +47655,54 @@ var ts; var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 24 /* CommaToken */: - return containingNodeKind === 211 /* VariableDeclaration */ || - containingNodeKind === 212 /* VariableDeclarationList */ || - containingNodeKind === 193 /* VariableStatement */ || - containingNodeKind === 217 /* EnumDeclaration */ || + return containingNodeKind === 213 /* VariableDeclaration */ || + containingNodeKind === 214 /* VariableDeclarationList */ || + containingNodeKind === 195 /* VariableStatement */ || + containingNodeKind === 219 /* EnumDeclaration */ || isFunction(containingNodeKind) || - containingNodeKind === 214 /* ClassDeclaration */ || - containingNodeKind === 186 /* ClassExpression */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 162 /* ArrayBindingPattern */ || - containingNodeKind === 216 /* TypeAliasDeclaration */; // type Map, K, | + containingNodeKind === 216 /* ClassDeclaration */ || + containingNodeKind === 188 /* ClassExpression */ || + containingNodeKind === 217 /* InterfaceDeclaration */ || + containingNodeKind === 164 /* ArrayBindingPattern */ || + containingNodeKind === 218 /* TypeAliasDeclaration */; // type Map, K, | case 21 /* DotToken */: - return containingNodeKind === 162 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 164 /* ArrayBindingPattern */; // var [.| case 54 /* ColonToken */: - return containingNodeKind === 163 /* BindingElement */; // var {x :html| + return containingNodeKind === 165 /* BindingElement */; // var {x :html| case 19 /* OpenBracketToken */: - return containingNodeKind === 162 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 164 /* ArrayBindingPattern */; // var [x| case 17 /* OpenParenToken */: - return containingNodeKind === 244 /* CatchClause */ || + return containingNodeKind === 246 /* CatchClause */ || isFunction(containingNodeKind); case 15 /* OpenBraceToken */: - return containingNodeKind === 217 /* EnumDeclaration */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 155 /* TypeLiteral */; // let x : { | + return containingNodeKind === 219 /* EnumDeclaration */ || + containingNodeKind === 217 /* InterfaceDeclaration */ || + containingNodeKind === 155 /* TypeLiteral */; // const x : { | case 23 /* SemicolonToken */: return containingNodeKind === 140 /* PropertySignature */ && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 215 /* InterfaceDeclaration */ || - contextToken.parent.parent.kind === 155 /* TypeLiteral */); // let x : { a; | + (contextToken.parent.parent.kind === 217 /* InterfaceDeclaration */ || + contextToken.parent.parent.kind === 155 /* TypeLiteral */); // const x : { a; | case 25 /* LessThanToken */: - return containingNodeKind === 214 /* ClassDeclaration */ || - containingNodeKind === 186 /* ClassExpression */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 216 /* TypeAliasDeclaration */ || + return containingNodeKind === 216 /* ClassDeclaration */ || + containingNodeKind === 188 /* ClassExpression */ || + containingNodeKind === 217 /* InterfaceDeclaration */ || + containingNodeKind === 218 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); case 113 /* StaticKeyword */: return containingNodeKind === 141 /* PropertyDeclaration */; case 22 /* DotDotDotToken */: return containingNodeKind === 138 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 162 /* ArrayBindingPattern */); // var [...z| + contextToken.parent.parent.kind === 164 /* ArrayBindingPattern */); // var [...z| case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: return containingNodeKind === 138 /* Parameter */; case 116 /* AsKeyword */: - return containingNodeKind === 226 /* ImportSpecifier */ || - containingNodeKind === 230 /* ExportSpecifier */ || - containingNodeKind === 224 /* NamespaceImport */; + return containingNodeKind === 228 /* ImportSpecifier */ || + containingNodeKind === 232 /* ExportSpecifier */ || + containingNodeKind === 226 /* NamespaceImport */; case 73 /* ClassKeyword */: case 81 /* EnumKeyword */: case 107 /* InterfaceKeyword */: @@ -46973,8 +47762,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_35 = element.propertyName || element.name; - exisingImportsOrExports[name_35.text] = true; + var name_31 = element.propertyName || element.name; + exisingImportsOrExports[name_31.text] = true; } if (ts.isEmpty(exisingImportsOrExports)) { return exportsOfModule; @@ -46995,9 +47784,10 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 245 /* PropertyAssignment */ && - m.kind !== 246 /* ShorthandPropertyAssignment */ && - m.kind !== 163 /* BindingElement */) { + if (m.kind !== 247 /* PropertyAssignment */ && + m.kind !== 248 /* ShorthandPropertyAssignment */ && + m.kind !== 165 /* BindingElement */ && + m.kind !== 143 /* MethodDeclaration */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -47005,7 +47795,7 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 163 /* BindingElement */ && m.propertyName) { + if (m.kind === 165 /* BindingElement */ && m.propertyName) { // include only identifiers in completion list if (m.propertyName.kind === 69 /* Identifier */) { existingName = m.propertyName.text; @@ -47035,7 +47825,7 @@ var ts; if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } - if (attr.kind === 238 /* JsxAttribute */) { + if (attr.kind === 240 /* JsxAttribute */) { seenNames[attr.name.text] = true; } } @@ -47074,10 +47864,10 @@ var ts; var entries = []; var target = program.getCompilerOptions().target; var nameTable = getNameTable(sourceFile); - for (var name_36 in nameTable) { - if (!uniqueNames[name_36]) { - uniqueNames[name_36] = name_36; - var displayName = getCompletionEntryDisplayName(name_36, target, /*performCharacterChecks:*/ true); + for (var name_32 in nameTable) { + if (!uniqueNames[name_32]) { + uniqueNames[name_32] = name_32; + var displayName = getCompletionEntryDisplayName(name_32, target, /*performCharacterChecks*/ true); if (displayName) { var entry = { name: displayName, @@ -47105,7 +47895,7 @@ var ts; // Try to get a valid display name for this symbol, if we could not find one, then ignore it. // We would like to only show things that can be added after a dot, so for instance numeric properties can // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks:*/ true, location); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks*/ true, location); if (!displayName) { return undefined; } @@ -47154,7 +47944,7 @@ var ts; // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks:*/ false, location_2) === entryName ? s : undefined; }); + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); if (symbol) { var _a = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location_2, location_2, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; return { @@ -47183,7 +47973,7 @@ var ts; function getSymbolKind(symbol, location) { var flags = symbol.getFlags(); if (flags & 32 /* Class */) - return ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 188 /* ClassExpression */) ? ScriptElementKind.localClassElement : ScriptElementKind.classElement; if (flags & 384 /* Enum */) return ScriptElementKind.enumElement; @@ -47248,7 +48038,7 @@ var ts; }); if (!unionPropertyKind) { // If this was union of all methods, - //make sure it has call signatures before we can label it as method + // make sure it has call signatures before we can label it as method var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (typeOfUnionProperty.getCallSignatures().length) { return ScriptElementKind.memberFunctionElement; @@ -47285,7 +48075,7 @@ var ts; var signature; type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 166 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 168 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -47294,7 +48084,7 @@ var ts; } // try get the call/construct signature from the type if it matches var callExpression; - if (location.kind === 168 /* CallExpression */ || location.kind === 169 /* NewExpression */) { + if (location.kind === 170 /* CallExpression */ || location.kind === 171 /* NewExpression */) { callExpression = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { @@ -47307,7 +48097,7 @@ var ts; // Use the first candidate: signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 169 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; + var useConstructSignatures = callExpression.kind === 171 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain @@ -47341,16 +48131,16 @@ var ts; case ScriptElementKind.parameterElement: case ScriptElementKind.localVariableElement: // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(ts.SyntaxKind.ColonToken)); + displayParts.push(ts.punctuationPart(54 /* ColonToken */)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(ts.SyntaxKind.NewKeyword)); + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - if (!(type.flags & ts.TypeFlags.Anonymous)) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, ts.SymbolFormatFlags.WriteTypeParametersOrArguments)); + if (!(type.flags & 65536 /* Anonymous */)) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); } - addSignatureDisplayParts(signature, allSignatures, ts.TypeFormatFlags.WriteArrowStyleSignature); + addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); break; default: // Just signature @@ -47386,7 +48176,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo) { - if (ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 188 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -47430,7 +48220,7 @@ var ts; } if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 218 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 220 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -47453,35 +48243,37 @@ var ts; } else { // Method/function type parameter - var container = ts.getContainingFunction(location); - if (container) { - var signatureDeclaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).parent; - var signature = typeChecker.getSignatureFromDeclaration(signatureDeclaration); - if (signatureDeclaration.kind === 148 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + var declaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */); + ts.Debug.assert(declaration !== undefined); + declaration = declaration.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); + if (declaration.kind === 148 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 147 /* CallSignature */ && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + } + else { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path + displayParts.push(ts.keywordPart(132 /* TypeKeyword */)); displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } - else if (signatureDeclaration.kind !== 147 /* CallSignature */ && signatureDeclaration.name) { - addFullSymbolName(signatureDeclaration.symbol); - } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); - } - else { - // Type aliash type parameter - // For example - // type list = T[]; // Both T will go through same code path - var declaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).parent; - displayParts.push(ts.keywordPart(132 /* TypeKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(declaration.symbol); - writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } } } if (symbolFlags & 8 /* EnumMember */) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 247 /* EnumMember */) { + if (declaration.kind === 249 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -47497,7 +48289,7 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 221 /* ImportEqualsDeclaration */) { + if (declaration.kind === 223 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -47630,9 +48422,10 @@ var ts; // Try getting just type at this position and show switch (node.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: case 135 /* QualifiedName */: case 97 /* ThisKeyword */: + case 161 /* ThisType */: case 95 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); @@ -47712,7 +48505,7 @@ var ts; var definition; ts.forEach(signatureDeclarations, function (d) { if ((selectConstructors && d.kind === 144 /* Constructor */) || - (!selectConstructors && (d.kind === 213 /* FunctionDeclaration */ || d.kind === 143 /* MethodDeclaration */ || d.kind === 142 /* MethodSignature */))) { + (!selectConstructors && (d.kind === 215 /* FunctionDeclaration */ || d.kind === 143 /* MethodDeclaration */ || d.kind === 142 /* MethodSignature */))) { declarations.push(d); if (d.body) definition = d; @@ -47781,7 +48574,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 246 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 248 /* ShorthandPropertyAssignment */) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -47857,10 +48650,11 @@ var ts; function getSemanticDocumentHighlights(node) { if (node.kind === 69 /* Identifier */ || node.kind === 97 /* ThisKeyword */ || + node.kind === 161 /* ThisType */ || node.kind === 95 /* SuperKeyword */ || isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) { - var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings*/ false, /*findInComments*/ false); return convertReferencedSymbols(referencedSymbols); } return undefined; @@ -47910,58 +48704,58 @@ var ts; switch (node.kind) { case 88 /* IfKeyword */: case 80 /* ElseKeyword */: - if (hasKind(node.parent, 196 /* IfStatement */)) { + if (hasKind(node.parent, 198 /* IfStatement */)) { return getIfElseOccurrences(node.parent); } break; case 94 /* ReturnKeyword */: - if (hasKind(node.parent, 204 /* ReturnStatement */)) { + if (hasKind(node.parent, 206 /* ReturnStatement */)) { return getReturnOccurrences(node.parent); } break; case 98 /* ThrowKeyword */: - if (hasKind(node.parent, 208 /* ThrowStatement */)) { + if (hasKind(node.parent, 210 /* ThrowStatement */)) { return getThrowOccurrences(node.parent); } break; case 72 /* CatchKeyword */: - if (hasKind(parent(parent(node)), 209 /* TryStatement */)) { + if (hasKind(parent(parent(node)), 211 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; case 100 /* TryKeyword */: case 85 /* FinallyKeyword */: - if (hasKind(parent(node), 209 /* TryStatement */)) { + if (hasKind(parent(node), 211 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent); } break; case 96 /* SwitchKeyword */: - if (hasKind(node.parent, 206 /* SwitchStatement */)) { + if (hasKind(node.parent, 208 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent); } break; case 71 /* CaseKeyword */: case 77 /* DefaultKeyword */: - if (hasKind(parent(parent(parent(node))), 206 /* SwitchStatement */)) { + if (hasKind(parent(parent(parent(node))), 208 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); } break; case 70 /* BreakKeyword */: case 75 /* ContinueKeyword */: - if (hasKind(node.parent, 203 /* BreakStatement */) || hasKind(node.parent, 202 /* ContinueStatement */)) { + if (hasKind(node.parent, 205 /* BreakStatement */) || hasKind(node.parent, 204 /* ContinueStatement */)) { return getBreakOrContinueStatementOccurrences(node.parent); } break; case 86 /* ForKeyword */: - if (hasKind(node.parent, 199 /* ForStatement */) || - hasKind(node.parent, 200 /* ForInStatement */) || - hasKind(node.parent, 201 /* ForOfStatement */)) { + if (hasKind(node.parent, 201 /* ForStatement */) || + hasKind(node.parent, 202 /* ForInStatement */) || + hasKind(node.parent, 203 /* ForOfStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 104 /* WhileKeyword */: case 79 /* DoKeyword */: - if (hasKind(node.parent, 198 /* WhileStatement */) || hasKind(node.parent, 197 /* DoStatement */)) { + if (hasKind(node.parent, 200 /* WhileStatement */) || hasKind(node.parent, 199 /* DoStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; @@ -47977,8 +48771,8 @@ var ts; } break; default: - if (ts.isModifier(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 193 /* VariableStatement */)) { + if (ts.isModifierKind(node.kind) && node.parent && + (ts.isDeclaration(node.parent) || node.parent.kind === 195 /* VariableStatement */)) { return getModifierOccurrences(node.kind, node.parent); } } @@ -47994,10 +48788,10 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 208 /* ThrowStatement */) { + if (node.kind === 210 /* ThrowStatement */) { statementAccumulator.push(node); } - else if (node.kind === 209 /* TryStatement */) { + else if (node.kind === 211 /* TryStatement */) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -48025,12 +48819,12 @@ var ts; var child = throwStatement; while (child.parent) { var parent_12 = child.parent; - if (ts.isFunctionBlock(parent_12) || parent_12.kind === 248 /* SourceFile */) { + if (ts.isFunctionBlock(parent_12) || parent_12.kind === 250 /* SourceFile */) { return parent_12; } // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. - if (parent_12.kind === 209 /* TryStatement */) { + if (parent_12.kind === 211 /* TryStatement */) { var tryStatement = parent_12; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; @@ -48045,7 +48839,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 203 /* BreakStatement */ || node.kind === 202 /* ContinueStatement */) { + if (node.kind === 205 /* BreakStatement */ || node.kind === 204 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -48060,16 +48854,16 @@ var ts; function getBreakOrContinueOwner(statement) { for (var node_2 = statement.parent; node_2; node_2 = node_2.parent) { switch (node_2.kind) { - case 206 /* SwitchStatement */: - if (statement.kind === 202 /* ContinueStatement */) { + case 208 /* SwitchStatement */: + if (statement.kind === 204 /* ContinueStatement */) { continue; } // Fall through. - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: - case 197 /* DoStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 200 /* WhileStatement */: + case 199 /* DoStatement */: if (!statement.label || isLabeledBy(node_2, statement.label.text)) { return node_2; } @@ -48088,24 +48882,24 @@ var ts; var container = declaration.parent; // Make sure we only highlight the keyword when it makes sense to do so. if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 214 /* ClassDeclaration */ || - container.kind === 186 /* ClassExpression */ || + if (!(container.kind === 216 /* ClassDeclaration */ || + container.kind === 188 /* ClassExpression */ || (declaration.kind === 138 /* Parameter */ && hasKind(container, 144 /* Constructor */)))) { return undefined; } } else if (modifier === 113 /* StaticKeyword */) { - if (!(container.kind === 214 /* ClassDeclaration */ || container.kind === 186 /* ClassExpression */)) { + if (!(container.kind === 216 /* ClassDeclaration */ || container.kind === 188 /* ClassExpression */)) { return undefined; } } else if (modifier === 82 /* ExportKeyword */ || modifier === 122 /* DeclareKeyword */) { - if (!(container.kind === 219 /* ModuleBlock */ || container.kind === 248 /* SourceFile */)) { + if (!(container.kind === 221 /* ModuleBlock */ || container.kind === 250 /* SourceFile */)) { return undefined; } } else if (modifier === 115 /* AbstractKeyword */) { - if (!(container.kind === 214 /* ClassDeclaration */ || declaration.kind === 214 /* ClassDeclaration */)) { + if (!(container.kind === 216 /* ClassDeclaration */ || declaration.kind === 216 /* ClassDeclaration */)) { return undefined; } } @@ -48117,8 +48911,8 @@ var ts; var modifierFlag = getFlagFromModifier(modifier); var nodes; switch (container.kind) { - case 219 /* ModuleBlock */: - case 248 /* SourceFile */: + case 221 /* ModuleBlock */: + case 250 /* SourceFile */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */) { nodes = declaration.members.concat(declaration); @@ -48130,8 +48924,8 @@ var ts; case 144 /* Constructor */: nodes = container.parameters.concat(container.parent.members); break; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -48214,7 +49008,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86 /* ForKeyword */, 104 /* WhileKeyword */, 79 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 197 /* DoStatement */) { + if (loopNode.kind === 199 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { @@ -48235,13 +49029,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -48295,7 +49089,7 @@ var ts; function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); // If we didn't find a containing function with a block body, bail out. - if (!(func && hasKind(func.body, 192 /* Block */))) { + if (!(func && hasKind(func.body, 194 /* Block */))) { return undefined; } var keywords = []; @@ -48311,7 +49105,7 @@ var ts; function getIfElseOccurrences(ifStatement) { var keywords = []; // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 196 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 198 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. @@ -48324,7 +49118,7 @@ var ts; break; } } - if (!hasKind(ifStatement.elseStatement, 196 /* IfStatement */)) { + if (!hasKind(ifStatement.elseStatement, 198 /* IfStatement */)) { break; } ifStatement = ifStatement.elseStatement; @@ -48400,11 +49194,11 @@ var ts; return convertReferences(referencedSymbols); } function getReferencesAtPosition(fileName, position) { - var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); return convertReferences(referencedSymbols); } function findReferences(fileName, position) { - var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); // Only include referenced symbols that have a valid definition. return ts.filter(referencedSymbols, function (rs) { return !!rs.definition; }); } @@ -48417,8 +49211,8 @@ var ts; } if (node.kind !== 69 /* Identifier */ && // TODO (drosen): This should be enabled in a later release - currently breaks rename. - //node.kind !== SyntaxKind.ThisKeyword && - //node.kind !== SyntaxKind.SuperKeyword && + // node.kind !== SyntaxKind.ThisKeyword && + // node.kind !== SyntaxKind.SuperKeyword && !isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && !isNameOfExternalModuleImportOrDeclaration(node)) { return undefined; @@ -48441,7 +49235,7 @@ var ts; return getLabelReferencesInNode(node.parent, node); } } - if (node.kind === 97 /* ThisKeyword */) { + if (node.kind === 97 /* ThisKeyword */ || node.kind === 161 /* ThisType */) { return getReferencesForThisKeyword(node, sourceFiles); } if (node.kind === 95 /* SuperKeyword */) { @@ -48475,8 +49269,8 @@ var ts; } else { var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); if (ts.lookUp(nameTable, internedName)) { @@ -48504,7 +49298,7 @@ var ts; } function isImportOrExportSpecifierImportSymbol(symbol) { return (symbol.flags & 8388608 /* Alias */) && ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 230 /* ExportSpecifier */; + return declaration.kind === 228 /* ImportSpecifier */ || declaration.kind === 232 /* ExportSpecifier */; }); } function getInternedName(symbol, location, declarations) { @@ -48531,14 +49325,14 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 173 /* FunctionExpression */ || valueDeclaration.kind === 186 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 175 /* FunctionExpression */ || valueDeclaration.kind === 188 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16 /* Private */) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 214 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 216 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. @@ -48551,7 +49345,7 @@ var ts; if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } - var scope = undefined; + var scope; var declarations = symbol.getDeclarations(); if (declarations) { for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { @@ -48564,7 +49358,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + if (container.kind === 250 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -48730,7 +49524,7 @@ var ts; } } function getReferencesForSuperKeyword(superKeyword) { - var searchSpaceNode = ts.getSuperContainer(superKeyword, /*includeFunctions*/ false); + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); if (!searchSpaceNode) { return undefined; } @@ -48759,7 +49553,7 @@ var ts; if (!node || node.kind !== 95 /* SuperKeyword */) { return; } - var container = ts.getSuperContainer(node, /*includeFunctions*/ false); + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); // If we have a 'super' container, we must have an enclosing class. // Now make sure the owning class is the same as the search-space // and has the same static qualifier as the original 'super's owner. @@ -48789,13 +49583,13 @@ var ts; staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 248 /* SourceFile */: + case 250 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // Fall through - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. @@ -48804,7 +49598,7 @@ var ts; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 248 /* SourceFile */) { + if (searchSpaceNode.kind === 250 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -48830,13 +49624,13 @@ var ts; ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 97 /* ThisKeyword */) { + if (!node || (node.kind !== 97 /* ThisKeyword */ && node.kind !== 161 /* ThisType */)) { return; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } @@ -48847,16 +49641,16 @@ var ts; result.push(getReferenceEntryFromNode(node)); } break; - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 216 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 64 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 248 /* SourceFile */: - if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + case 250 /* SourceFile */: + if (container.kind === 250 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -48883,8 +49677,8 @@ var ts; * property name and variable declaration of the identifier. * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service * should show both 'name' in 'obj' and 'name' in variable declaration - * let name = "Foo"; - * let obj = { name }; + * const name = "Foo"; + * const obj = { name }; * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. @@ -48894,6 +49688,14 @@ var ts; result.push(shorthandValueSymbol); } } + // If the symbol.valueDeclaration is a property parameter declaration, + // we should include both parameter declaration symbol and property declaration symbol + // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in contructor.locals. + // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 138 /* Parameter */ && + ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); + } // If this is a union property, add all the symbols from all its source symbols in all unioned types. // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { @@ -48910,11 +49712,11 @@ var ts; function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { if (symbol && symbol.flags & (32 /* Class */ | 64 /* Interface */)) { ts.forEach(symbol.getDeclarations(), function (declaration) { - if (declaration.kind === 214 /* ClassDeclaration */) { + if (declaration.kind === 216 /* ClassDeclaration */) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 215 /* InterfaceDeclaration */) { + else if (declaration.kind === 217 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -48975,19 +49777,19 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_37 = node.text; + var name_33 = node.text; if (contextualType) { if (contextualType.flags & 16384 /* Union */) { // This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types) // if not, search the constituent types for the property - var unionProperty = contextualType.getProperty(name_37); + var unionProperty = contextualType.getProperty(name_33); if (unionProperty) { return [unionProperty]; } else { var result_4 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_37); + var symbol = t.getProperty(name_33); if (symbol) { result_4.push(symbol); } @@ -48996,7 +49798,7 @@ var ts; } } else { - var symbol_1 = contextualType.getProperty(name_37); + var symbol_1 = contextualType.getProperty(name_33); if (symbol_1) { return [symbol_1]; } @@ -49054,10 +49856,10 @@ var ts; } var parent = node.parent; if (parent) { - if (parent.kind === 180 /* PostfixUnaryExpression */ || parent.kind === 179 /* PrefixUnaryExpression */) { + if (parent.kind === 182 /* PostfixUnaryExpression */ || parent.kind === 181 /* PrefixUnaryExpression */) { return true; } - else if (parent.kind === 181 /* BinaryExpression */ && parent.left === node) { + else if (parent.kind === 183 /* BinaryExpression */ && parent.left === node) { var operator = parent.operatorToken.kind; return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; } @@ -49069,9 +49871,6 @@ var ts; synchronizeHostData(); return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount); } - function containErrors(diagnostics) { - return ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); - } function getEmitOutput(fileName) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -49092,32 +49891,32 @@ var ts; function getMeaningFromDeclaration(node) { switch (node.kind) { case 138 /* Parameter */: - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 246 /* ShorthandPropertyAssignment */: - case 247 /* EnumMember */: + case 247 /* PropertyAssignment */: + case 248 /* ShorthandPropertyAssignment */: + case 249 /* EnumMember */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 244 /* CatchClause */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 246 /* CatchClause */: return 1 /* Value */; case 137 /* TypeParameter */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: + case 217 /* InterfaceDeclaration */: + case 218 /* TypeAliasDeclaration */: case 155 /* TypeLiteral */: return 2 /* Type */; - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: if (node.name.kind === 9 /* StringLiteral */) { return 4 /* Namespace */ | 1 /* Value */; } @@ -49127,15 +49926,15 @@ var ts; else { return 4 /* Namespace */; } - case 225 /* NamedImports */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 222 /* ImportDeclaration */: - case 227 /* ExportAssignment */: - case 228 /* ExportDeclaration */: + case 227 /* NamedImports */: + case 228 /* ImportSpecifier */: + case 223 /* ImportEqualsDeclaration */: + case 224 /* ImportDeclaration */: + case 229 /* ExportAssignment */: + case 230 /* ExportDeclaration */: return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; // An external module can be a Value - case 248 /* SourceFile */: + case 250 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; @@ -49145,8 +49944,9 @@ var ts; node = node.parent; } return node.parent.kind === 151 /* TypeReference */ || - (node.parent.kind === 188 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node); + (node.parent.kind === 190 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node)) || + node.kind === 161 /* ThisType */; } function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); @@ -49154,16 +49954,16 @@ var ts; function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 166 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 166 /* PropertyAccessExpression */) { + if (root.parent.kind === 168 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 168 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 188 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 243 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 190 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 245 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 214 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || - (decl.kind === 215 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); + return (decl.kind === 216 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || + (decl.kind === 217 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); } return false; } @@ -49191,13 +49991,13 @@ var ts; // import a = |b.c|.d; // Namespace if (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 221 /* ImportEqualsDeclaration */) { + node.parent.parent.kind === 223 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; } function getMeaningFromLocation(node) { - if (node.parent.kind === 227 /* ExportAssignment */) { + if (node.parent.kind === 229 /* ExportAssignment */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } else if (isInRightSideOfImport(node)) { @@ -49237,14 +50037,16 @@ var ts; return; } switch (node.kind) { - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: case 135 /* QualifiedName */: case 9 /* StringLiteral */: + case 162 /* StringLiteralType */: case 84 /* FalseKeyword */: case 99 /* TrueKeyword */: case 93 /* NullKeyword */: case 95 /* SuperKeyword */: case 97 /* ThisKeyword */: + case 161 /* ThisType */: case 69 /* Identifier */: break; // Cant create the text span @@ -49261,7 +50063,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 218 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 220 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -49285,7 +50087,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -49302,10 +50104,10 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 220 /* ModuleDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 215 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -49359,7 +50161,7 @@ var ts; */ function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 218 /* ModuleDeclaration */ && + return declaration.kind === 220 /* ModuleDeclaration */ && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; }); } @@ -49433,8 +50235,8 @@ var ts; var spanStart = span.start; var spanLength = span.length; // Make a scanner we can get trivia from. - var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; @@ -49517,16 +50319,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); pos = tag.tagName.end; switch (tag.kind) { - case 267 /* JSDocParameterTag */: + case 269 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 270 /* JSDocTemplateTag */: + case 272 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 269 /* JSDocTypeTag */: + case 271 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 268 /* JSDocReturnTag */: + case 270 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -49617,16 +50419,16 @@ var ts; if (token) { if (tokenKind === 56 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 211 /* VariableDeclaration */ || + if (token.parent.kind === 213 /* VariableDeclaration */ || token.parent.kind === 141 /* PropertyDeclaration */ || token.parent.kind === 138 /* Parameter */) { return 5 /* operator */; } } - if (token.parent.kind === 181 /* BinaryExpression */ || - token.parent.kind === 179 /* PrefixUnaryExpression */ || - token.parent.kind === 180 /* PostfixUnaryExpression */ || - token.parent.kind === 182 /* ConditionalExpression */) { + if (token.parent.kind === 183 /* BinaryExpression */ || + token.parent.kind === 181 /* PrefixUnaryExpression */ || + token.parent.kind === 182 /* PostfixUnaryExpression */ || + token.parent.kind === 184 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -49635,7 +50437,7 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */) { + else if (tokenKind === 9 /* StringLiteral */ || tokenKind === 162 /* StringLiteralType */) { return 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { @@ -49649,7 +50451,7 @@ var ts; else if (tokenKind === 69 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } @@ -49659,17 +50461,17 @@ var ts; return 15 /* typeParameterName */; } return; - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } @@ -49679,17 +50481,17 @@ var ts; return 17 /* parameterName */; } return; - case 235 /* JsxOpeningElement */: + case 237 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } return; - case 237 /* JsxClosingElement */: + case 239 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } return; - case 234 /* JsxSelfClosingElement */: + case 236 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } @@ -49818,7 +50620,6 @@ var ts; * be performed. */ function getDocCommentTemplateAtPosition(fileName, position) { - var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Check if in a context where we don't want to perform any insertion if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { @@ -49837,19 +50638,19 @@ var ts; var commentOwner; findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 144 /* Constructor */: - case 214 /* ClassDeclaration */: - case 193 /* VariableStatement */: + case 216 /* ClassDeclaration */: + case 195 /* VariableStatement */: break findOwner; - case 248 /* SourceFile */: + case 250 /* SourceFile */: return undefined; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - if (commentOwner.parent.kind === 218 /* ModuleDeclaration */) { + if (commentOwner.parent.kind === 220 /* ModuleDeclaration */) { return undefined; } break findOwner; @@ -49891,7 +50692,7 @@ var ts; if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } - if (commentOwner.kind === 193 /* VariableStatement */) { + if (commentOwner.kind === 195 /* VariableStatement */) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { @@ -49909,14 +50710,14 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 172 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 174 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return rightHandSide.parameters; - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 144 /* Constructor */) { @@ -50065,12 +50866,17 @@ var ts; if (declarations && declarations.length > 0) { // Disallow rename for elements that are defined in the standard TypeScript library. var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); + var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); if (defaultLibFileName) { for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { var current = declarations_10[_i]; var sourceFile_2 = current.getSourceFile(); + // TODO (drosen): When is there no source file? + if (!sourceFile_2) { + continue; + } var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); - if (sourceFile_2 && getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { + if (canonicalName === canonicalDefaultLibName) { return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); } } @@ -50080,10 +50886,10 @@ var ts; if (kind) { return { canRename: true, - localizedErrorMessage: undefined, - displayName: displayName, - fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kind: kind, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kindModifiers: getSymbolModifiers(symbol), triggerSpan: ts.createTextSpan(node.getStart(), node.getWidth()) }; @@ -50168,7 +50974,7 @@ var ts; // then we want 'something' to be in the name table. Similarly, if we have // "a['propname']" then we want to store "propname" in the name table. if (ts.isDeclarationName(node) || - node.parent.kind === 232 /* ExternalModuleReference */ || + node.parent.kind === 234 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node)) { nameTable[node.text] = node.text; } @@ -50181,7 +50987,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 167 /* ElementAccessExpression */ && + node.parent.kind === 169 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /// Classifier @@ -50310,7 +51116,7 @@ var ts; // (and a newline). That way when we lex we'll think we're still in a multiline comment. switch (lexState) { case 3 /* InDoubleQuoteStringLiteral */: - text = '"\\\n' + text; + text = "\"\\\n" + text; offset = 3; break; case 2 /* InSingleQuoteStringLiteral */: @@ -50440,7 +51246,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */ || token === 162 /* StringLiteralType */) { // Check to see if we finished up on a multiline string literal. var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { @@ -50579,6 +51385,7 @@ var ts; case 8 /* NumericLiteral */: return 4 /* numericLiteral */; case 9 /* StringLiteral */: + case 162 /* StringLiteralType */: return 6 /* stringLiteral */; case 10 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; @@ -50645,7 +51452,7 @@ var ts; } var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) { + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line // eg: let x =10; |--- cursor is here // let y = 10; @@ -50664,14 +51471,20 @@ var ts; // Get the span in the node based on its syntax return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - return ts.createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd()); + var start = startNode.decorators ? + ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + startNode.getStart(sourceFile); + return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { - if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { return spanInNode(node); } return spanInNode(otherwiseOnNode); } + function spanInNodeArray(nodeArray) { + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } @@ -50681,125 +51494,131 @@ var ts; function spanInNode(node) { if (node) { if (ts.isExpression(node)) { - if (node.parent.kind === 197 /* DoStatement */) { + if (node.parent.kind === 199 /* DoStatement */) { // Set span as if on while keyword return spanInPreviousNode(node); } - if (node.parent.kind === 199 /* ForStatement */) { + if (node.parent.kind === 139 /* Decorator */) { + // Set breakpoint on the decorator emit + return spanInNode(node.parent); + } + if (node.parent.kind === 201 /* ForStatement */) { // For now lets set the span on this expression, fix it later return textSpan(node); } - if (node.parent.kind === 181 /* BinaryExpression */ && node.parent.operatorToken.kind === 24 /* CommaToken */) { + if (node.parent.kind === 183 /* BinaryExpression */ && node.parent.operatorToken.kind === 24 /* CommaToken */) { // if this is comma expression, the breakpoint is possible in this expression return textSpan(node); } - if (node.parent.kind === 174 /* ArrowFunction */ && node.parent.body === node) { + if (node.parent.kind === 176 /* ArrowFunction */ && node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); } } switch (node.kind) { - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return spanInVariableDeclaration(node); case 138 /* Parameter */: return spanInParameterDeclaration(node); - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 144 /* Constructor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 192 /* Block */: + case 194 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // Fall through - case 219 /* ModuleBlock */: + case 221 /* ModuleBlock */: return spanInBlock(node); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return spanInBlock(node.block); - case 195 /* ExpressionStatement */: + case 197 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 204 /* ReturnStatement */: + case 206 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 198 /* WhileStatement */: + case 200 /* WhileStatement */: // Span on while(...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 197 /* DoStatement */: + case 199 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 210 /* DebuggerStatement */: + case 212 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 196 /* IfStatement */: + case 198 /* IfStatement */: // set on if(..) span return textSpan(node, ts.findNextToken(node.expression, node)); - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: + case 205 /* BreakStatement */: + case 204 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 199 /* ForStatement */: + case 201 /* ForStatement */: return spanInForStatement(node); - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: // span on for (a in ...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: // span on switch(...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 209 /* TryStatement */: + case 211 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 208 /* ThrowStatement */: + case 210 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 249 /* EnumMember */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: // span on complete node return textSpan(node); - case 205 /* WithStatement */: + case 207 /* WithStatement */: // span in statement return spanInNode(node.statement); + case 139 /* Decorator */: + return spanInNodeArray(node.parent.decorators); // No breakpoint in interface, type alias - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: + case 217 /* InterfaceDeclaration */: + case 218 /* TypeAliasDeclaration */: return undefined; // Tokens: case 23 /* SemicolonToken */: @@ -50829,11 +51648,11 @@ var ts; return spanInNextNode(node); default: // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 245 /* PropertyAssignment */ && node.parent.name === node) { + if (node.parent.kind === 247 /* PropertyAssignment */ && node.parent.name === node) { return spanInNode(node.parent.initializer); } // Breakpoint in type assertion goes to its operand - if (node.parent.kind === 171 /* TypeAssertionExpression */ && node.parent.type === node) { + if (node.parent.kind === 173 /* TypeAssertionExpression */ && node.parent.type === node) { return spanInNode(node.parent.expression); } // return type of function go to previous token @@ -50846,12 +51665,12 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 200 /* ForInStatement */ || - variableDeclaration.parent.parent.kind === 201 /* ForOfStatement */) { + if (variableDeclaration.parent.parent.kind === 202 /* ForInStatement */ || + variableDeclaration.parent.parent.kind === 203 /* ForOfStatement */) { return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.parent.kind === 193 /* VariableStatement */; - var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 199 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); + var isParentVariableStatement = variableDeclaration.parent.parent.kind === 195 /* VariableStatement */; + var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 201 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); var declarations = isParentVariableStatement ? variableDeclaration.parent.parent.declarationList.declarations : isDeclarationOfForStatement @@ -50905,7 +51724,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return !!(functionDeclaration.flags & 2 /* Export */) || - (functionDeclaration.parent.kind === 214 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */); + (functionDeclaration.parent.kind === 216 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -50928,18 +51747,18 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement - case 198 /* WhileStatement */: - case 196 /* IfStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 200 /* WhileStatement */: + case 198 /* IfStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 199 /* ForStatement */: + case 201 /* ForStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement @@ -50947,7 +51766,7 @@ var ts; } function spanInForStatement(forStatement) { if (forStatement.initializer) { - if (forStatement.initializer.kind === 212 /* VariableDeclarationList */) { + if (forStatement.initializer.kind === 214 /* VariableDeclarationList */) { var variableDeclarationList = forStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); @@ -50967,13 +51786,13 @@ var ts; // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 220 /* CaseBlock */: + case 222 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -50981,24 +51800,24 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 219 /* ModuleBlock */: + case 221 /* ModuleBlock */: // If this is not instantiated module block no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } - case 217 /* EnumDeclaration */: - case 214 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 192 /* Block */: + case 194 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // fall through. - case 244 /* CatchClause */: + case 246 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 220 /* CaseBlock */: + case 222 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -51012,7 +51831,7 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 197 /* DoStatement */) { + if (node.parent.kind === 199 /* DoStatement */) { // Go to while keyword and do action instead return spanInPreviousNode(node); } @@ -51022,17 +51841,17 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 176 /* ArrowFunction */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 144 /* Constructor */: - case 198 /* WhileStatement */: - case 197 /* DoStatement */: - case 199 /* ForStatement */: + case 200 /* WhileStatement */: + case 199 /* DoStatement */: + case 201 /* ForStatement */: return spanInPreviousNode(node); // Default to parent node default: @@ -51041,19 +51860,19 @@ var ts; } function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration - if (ts.isFunctionLike(node.parent) || node.parent.kind === 245 /* PropertyAssignment */) { + if (ts.isFunctionLike(node.parent) || node.parent.kind === 247 /* PropertyAssignment */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 171 /* TypeAssertionExpression */) { + if (node.parent.kind === 173 /* TypeAssertionExpression */) { return spanInNode(node.parent.expression); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 197 /* DoStatement */) { + if (node.parent.kind === 199 /* DoStatement */) { // Set span on while expression return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); } @@ -51082,6 +51901,9 @@ var ts; /// /* @internal */ var debugObjectHost = this; +// We need to use 'null' to interface with the managed side. +/* tslint:disable:no-null */ +/* tslint:disable:no-in-operator */ /* @internal */ var ts; (function (ts) { @@ -51093,7 +51915,6 @@ var ts; var ScriptSnapshotShimAdapter = (function () { function ScriptSnapshotShimAdapter(scriptSnapshotShim) { this.scriptSnapshotShim = scriptSnapshotShim; - this.lineStartPositions = null; } ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { return this.scriptSnapshotShim.getText(start, end); @@ -51119,7 +51940,7 @@ var ts; } }; return ScriptSnapshotShimAdapter; - })(); + }()); var LanguageServiceShimHostAdapter = (function () { function LanguageServiceShimHostAdapter(shimHost) { var _this = this; @@ -51137,6 +51958,9 @@ var ts; }); }; } + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } LanguageServiceShimHostAdapter.prototype.log = function (s) { if (this.loggingEnabled) { @@ -51174,11 +51998,6 @@ var ts; return this.files = JSON.parse(encoded); }; LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { - // Shim the API changes for 1.5 release. This should be removed once - // TypeScript 1.5 has shipped. - if (this.files && this.files.indexOf(fileName) < 0) { - return undefined; - } var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); }; @@ -51206,17 +52025,10 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { - // Wrap the API changes for 1.5 release. This try/catch - // should be removed once TypeScript 1.5 has shipped. - try { - return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); - } - catch (e) { - return ""; - } + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; return LanguageServiceShimHostAdapter; - })(); + }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; /** A cancellation that throttles calls to the host */ var ThrottledCancellationToken = (function () { @@ -51238,23 +52050,17 @@ var ts; return false; }; return ThrottledCancellationToken; - })(); + }()); var CoreServicesShimHostAdapter = (function () { function CoreServicesShimHostAdapter(shimHost) { + var _this = this; this.shimHost = shimHost; + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude) { - // Wrap the API changes for 1.5 release. This try/catch - // should be removed once TypeScript 1.5 has shipped. - // Also consider removing the optional designation for - // the exclude param at this time. - var encoded; - try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); - } - catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension); - } + var encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -51264,18 +52070,19 @@ var ts; return this.shimHost.readFile(fileName); }; return CoreServicesShimHostAdapter; - })(); + }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; function simpleForwardCall(logger, actionDescription, action, logPerformance) { + var start; if (logPerformance) { logger.log(actionDescription); - var start = Date.now(); + start = Date.now(); } var result = action(); if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); - if (typeof (result) === "string") { + if (typeof result === "string") { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; @@ -51308,7 +52115,7 @@ var ts; this.factory.unregisterShim(this); }; return ShimBase; - })(); + }()); function realizeDiagnostics(diagnostics, newLine) { return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); } @@ -51357,9 +52164,7 @@ var ts; * Update the list of scripts known to the compiler */ LanguageServiceShimObject.prototype.refresh = function (throwOnError) { - this.forwardJSONCall("refresh(" + throwOnError + ")", function () { - return null; - }); + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); }; LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { var _this = this; @@ -51374,33 +52179,25 @@ var ts; }; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { var _this = this; @@ -51430,10 +52227,7 @@ var ts; */ LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { - var quickInfo = _this.languageService.getQuickInfoAtPosition(fileName, position); - return quickInfo; - }); + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); }; /// NAMEORDOTTEDNAMESPAN /** @@ -51442,10 +52236,7 @@ var ts; */ LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { var _this = this; - return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { - var spanInfo = _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); - return spanInfo; - }); + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); }; /** * STATEMENTSPAN @@ -51453,18 +52244,12 @@ var ts; */ LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { - var spanInfo = _this.languageService.getBreakpointStatementAtPosition(fileName, position); - return spanInfo; - }); + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; /// SIGNATUREHELP LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { - var signatureInfo = _this.languageService.getSignatureHelpItems(fileName, position); - return signatureInfo; - }); + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); }); }; /// GOTO DEFINITION /** @@ -51473,9 +52258,7 @@ var ts; */ LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; /// GOTO Type /** @@ -51484,29 +52267,20 @@ var ts; */ LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getTypeDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { - return _this.languageService.getRenameInfo(fileName, position); - }); + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); }; LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { var _this = this; - return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { - return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); - }); + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); }; /// GET BRACE MATCHING LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { - var textRanges = _this.languageService.getBraceMatchingAtPosition(fileName, position); - return textRanges; - }); + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); }; /// GET SMART INDENT LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { @@ -51519,21 +52293,15 @@ var ts; /// GET REFERENCES LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getReferencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { var _this = this; - return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { - return _this.languageService.findReferences(fileName, position); - }); + return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); }); }; LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getOccurrencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { var _this = this; @@ -51552,41 +52320,32 @@ var ts; */ LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { - var completion = _this.languageService.getCompletionsAtPosition(fileName, position); - return completion; - }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); }; /** Get a string based representation of a completion list entry details */ LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", " + entryName + ")", function () { - var details = _this.languageService.getCompletionEntryDetails(fileName, position, entryName); - return details; - }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); - return edits; + return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForDocument(fileName, localOptions); - return edits; + return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); - return edits; + return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { @@ -51597,45 +52356,27 @@ var ts; /** Return a list of symbols that are interesting to navigate to */ LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount) { var _this = this; - return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { - var items = _this.languageService.getNavigateToItems(searchValue, maxResultCount); - return items; - }); + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; - return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { - var items = _this.languageService.getNavigationBarItems(fileName); - return items; - }); + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; - return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { - var items = _this.languageService.getOutliningSpans(fileName); - return items; - }); + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); }; LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { var _this = this; - return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { - var items = _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); - return items; - }); + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); }; /// Emit LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { var _this = this; - return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { - var output = _this.languageService.getEmitOutput(fileName); - // Shim the API changes for 1.5 release. This should be removed once - // TypeScript 1.5 has shipped. - output.emitOutputStatus = output.emitSkipped ? 1 : 0; - return output; - }); + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); }; return LanguageServiceShimObject; - })(ShimBase); + }(ShimBase)); function convertClassifications(classifications) { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } @@ -51654,17 +52395,17 @@ var ts; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); - var items = classification.entries; var result = ""; - for (var i = 0; i < items.length; i++) { - result += items[i].length + "\n"; - result += items[i].classification + "\n"; + for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { + var item = _a[_i]; + result += item.length + "\n"; + result += item.classification + "\n"; } result += classification.finalLexState; return result; }; return ClassifierShimObject; - })(ShimBase); + }(ShimBase)); var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { @@ -51723,24 +52464,22 @@ var ts; return { options: {}, files: [], - errors: [realizeDiagnostic(result.error, '\r\n')] + errors: [realizeDiagnostic(result.error, "\r\n")] }; } var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(ts.normalizeSlashes(fileName))); return { options: configFile.options, files: configFile.fileNames, - errors: realizeDiagnostics(configFile.errors, '\r\n') + errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); }; CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { - return this.forwardJSONCall("getDefaultCompilationSettings()", function () { - return ts.getDefaultCompilerOptions(); - }); + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); }); }; return CoreServicesShimObject; - })(ShimBase); + }(ShimBase)); var TypeScriptServicesFactory = (function () { function TypeScriptServicesFactory() { this._shims = []; @@ -51802,12 +52541,14 @@ var ts; throw new Error("Invalid operation"); }; return TypeScriptServicesFactory; - })(); + }()); ts.TypeScriptServicesFactory = TypeScriptServicesFactory; if (typeof module !== "undefined" && module.exports) { module.exports = ts; } })(ts || (ts = {})); +/* tslint:enable:no-in-operator */ +/* tslint:enable:no-null */ /// TODO: this is used by VS, clean this up on both sides of the interface /* @internal */ var TypeScript; @@ -51817,5 +52558,9 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); +/* tslint:disable:no-unused-variable */ +// '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.6"; +var toolsVersion = "1.8"; +/* tslint:enable:no-unused-variable */ diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index af9a8bffe35..797f9ec728c 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -194,118 +194,120 @@ declare namespace ts { UnionType = 158, IntersectionType = 159, ParenthesizedType = 160, - ObjectBindingPattern = 161, - ArrayBindingPattern = 162, - BindingElement = 163, - ArrayLiteralExpression = 164, - ObjectLiteralExpression = 165, - PropertyAccessExpression = 166, - ElementAccessExpression = 167, - CallExpression = 168, - NewExpression = 169, - TaggedTemplateExpression = 170, - TypeAssertionExpression = 171, - ParenthesizedExpression = 172, - FunctionExpression = 173, - ArrowFunction = 174, - DeleteExpression = 175, - TypeOfExpression = 176, - VoidExpression = 177, - AwaitExpression = 178, - PrefixUnaryExpression = 179, - PostfixUnaryExpression = 180, - BinaryExpression = 181, - ConditionalExpression = 182, - TemplateExpression = 183, - YieldExpression = 184, - SpreadElementExpression = 185, - ClassExpression = 186, - OmittedExpression = 187, - ExpressionWithTypeArguments = 188, - AsExpression = 189, - TemplateSpan = 190, - SemicolonClassElement = 191, - Block = 192, - VariableStatement = 193, - EmptyStatement = 194, - ExpressionStatement = 195, - IfStatement = 196, - DoStatement = 197, - WhileStatement = 198, - ForStatement = 199, - ForInStatement = 200, - ForOfStatement = 201, - ContinueStatement = 202, - BreakStatement = 203, - ReturnStatement = 204, - WithStatement = 205, - SwitchStatement = 206, - LabeledStatement = 207, - ThrowStatement = 208, - TryStatement = 209, - DebuggerStatement = 210, - VariableDeclaration = 211, - VariableDeclarationList = 212, - FunctionDeclaration = 213, - ClassDeclaration = 214, - InterfaceDeclaration = 215, - TypeAliasDeclaration = 216, - EnumDeclaration = 217, - ModuleDeclaration = 218, - ModuleBlock = 219, - CaseBlock = 220, - ImportEqualsDeclaration = 221, - ImportDeclaration = 222, - ImportClause = 223, - NamespaceImport = 224, - NamedImports = 225, - ImportSpecifier = 226, - ExportAssignment = 227, - ExportDeclaration = 228, - NamedExports = 229, - ExportSpecifier = 230, - MissingDeclaration = 231, - ExternalModuleReference = 232, - JsxElement = 233, - JsxSelfClosingElement = 234, - JsxOpeningElement = 235, - JsxText = 236, - JsxClosingElement = 237, - JsxAttribute = 238, - JsxSpreadAttribute = 239, - JsxExpression = 240, - CaseClause = 241, - DefaultClause = 242, - HeritageClause = 243, - CatchClause = 244, - PropertyAssignment = 245, - ShorthandPropertyAssignment = 246, - EnumMember = 247, - SourceFile = 248, - JSDocTypeExpression = 249, - JSDocAllType = 250, - JSDocUnknownType = 251, - JSDocArrayType = 252, - JSDocUnionType = 253, - JSDocTupleType = 254, - JSDocNullableType = 255, - JSDocNonNullableType = 256, - JSDocRecordType = 257, - JSDocRecordMember = 258, - JSDocTypeReference = 259, - JSDocOptionalType = 260, - JSDocFunctionType = 261, - JSDocVariadicType = 262, - JSDocConstructorType = 263, - JSDocThisType = 264, - JSDocComment = 265, - JSDocTag = 266, - JSDocParameterTag = 267, - JSDocReturnTag = 268, - JSDocTypeTag = 269, - JSDocTemplateTag = 270, - SyntaxList = 271, - Count = 272, + ThisType = 161, + StringLiteralType = 162, + ObjectBindingPattern = 163, + ArrayBindingPattern = 164, + BindingElement = 165, + ArrayLiteralExpression = 166, + ObjectLiteralExpression = 167, + PropertyAccessExpression = 168, + ElementAccessExpression = 169, + CallExpression = 170, + NewExpression = 171, + TaggedTemplateExpression = 172, + TypeAssertionExpression = 173, + ParenthesizedExpression = 174, + FunctionExpression = 175, + ArrowFunction = 176, + DeleteExpression = 177, + TypeOfExpression = 178, + VoidExpression = 179, + AwaitExpression = 180, + PrefixUnaryExpression = 181, + PostfixUnaryExpression = 182, + BinaryExpression = 183, + ConditionalExpression = 184, + TemplateExpression = 185, + YieldExpression = 186, + SpreadElementExpression = 187, + ClassExpression = 188, + OmittedExpression = 189, + ExpressionWithTypeArguments = 190, + AsExpression = 191, + TemplateSpan = 192, + SemicolonClassElement = 193, + Block = 194, + VariableStatement = 195, + EmptyStatement = 196, + ExpressionStatement = 197, + IfStatement = 198, + DoStatement = 199, + WhileStatement = 200, + ForStatement = 201, + ForInStatement = 202, + ForOfStatement = 203, + ContinueStatement = 204, + BreakStatement = 205, + ReturnStatement = 206, + WithStatement = 207, + SwitchStatement = 208, + LabeledStatement = 209, + ThrowStatement = 210, + TryStatement = 211, + DebuggerStatement = 212, + VariableDeclaration = 213, + VariableDeclarationList = 214, + FunctionDeclaration = 215, + ClassDeclaration = 216, + InterfaceDeclaration = 217, + TypeAliasDeclaration = 218, + EnumDeclaration = 219, + ModuleDeclaration = 220, + ModuleBlock = 221, + CaseBlock = 222, + ImportEqualsDeclaration = 223, + ImportDeclaration = 224, + ImportClause = 225, + NamespaceImport = 226, + NamedImports = 227, + ImportSpecifier = 228, + ExportAssignment = 229, + ExportDeclaration = 230, + NamedExports = 231, + ExportSpecifier = 232, + MissingDeclaration = 233, + ExternalModuleReference = 234, + JsxElement = 235, + JsxSelfClosingElement = 236, + JsxOpeningElement = 237, + JsxText = 238, + JsxClosingElement = 239, + JsxAttribute = 240, + JsxSpreadAttribute = 241, + JsxExpression = 242, + CaseClause = 243, + DefaultClause = 244, + HeritageClause = 245, + CatchClause = 246, + PropertyAssignment = 247, + ShorthandPropertyAssignment = 248, + EnumMember = 249, + SourceFile = 250, + JSDocTypeExpression = 251, + JSDocAllType = 252, + JSDocUnknownType = 253, + JSDocArrayType = 254, + JSDocUnionType = 255, + JSDocTupleType = 256, + JSDocNullableType = 257, + JSDocNonNullableType = 258, + JSDocRecordType = 259, + JSDocRecordMember = 260, + JSDocTypeReference = 261, + JSDocOptionalType = 262, + JSDocFunctionType = 263, + JSDocVariadicType = 264, + JSDocConstructorType = 265, + JSDocThisType = 266, + JSDocComment = 267, + JSDocTag = 268, + JSDocParameterTag = 269, + JSDocReturnTag = 270, + JSDocTypeTag = 271, + JSDocTemplateTag = 272, + SyntaxList = 273, + Count = 274, FirstAssignment = 56, LastAssignment = 68, FirstReservedWord = 70, @@ -314,8 +316,8 @@ declare namespace ts { LastKeyword = 134, FirstFutureReservedWord = 106, LastFutureReservedWord = 114, - FirstTypeNode = 151, - LastTypeNode = 160, + FirstTypeNode = 150, + LastTypeNode = 162, FirstPunctuation = 15, LastPunctuation = 68, FirstToken = 0, @@ -359,10 +361,14 @@ declare namespace ts { } enum JsxFlags { None = 0, + /** An element from a named property of the JSX.IntrinsicElements interface */ IntrinsicNamedElement = 1, + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, - ClassElement = 4, - UnknownElement = 8, + /** An element backed by a class, class-like, or function value */ + ValueElement = 4, + /** Element resolution failed */ + UnknownElement = 16, IntrinsicElement = 3, } interface Node extends TextRange { @@ -375,9 +381,11 @@ declare namespace ts { interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface ModifiersArray extends NodeArray { + interface ModifiersArray extends NodeArray { flags: number; } + interface Modifier extends Node { + } interface Identifier extends PrimaryExpression { text: string; originalKeywordKind?: SyntaxKind; @@ -393,6 +401,9 @@ declare namespace ts { _declarationBrand: any; name?: DeclarationName; } + interface DeclarationStatement extends Declaration, Statement { + name?: Identifier; + } interface ComputedPropertyName extends Node { expression: Expression; } @@ -405,10 +416,15 @@ declare namespace ts { expression?: Expression; } interface SignatureDeclaration extends Declaration { + name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; type?: TypeNode; } + interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + } + interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + } interface VariableDeclaration extends Declaration { parent?: VariableDeclarationList; name: Identifier | BindingPattern; @@ -431,18 +447,25 @@ declare namespace ts { name: Identifier | BindingPattern; initializer?: Expression; } - interface PropertyDeclaration extends Declaration, ClassElement { - name: DeclarationName; + interface PropertySignature extends TypeElement { + name: PropertyName; questionToken?: Node; type?: TypeNode; initializer?: Expression; } + interface PropertyDeclaration extends ClassElement { + questionToken?: Node; + name: PropertyName; + type?: TypeNode; + initializer?: Expression; + } interface ObjectLiteralElement extends Declaration { _objectLiteralBrandBrand: any; + name?: PropertyName; } interface PropertyAssignment extends ObjectLiteralElement { _propertyAssignmentBrand: any; - name: DeclarationName; + name: PropertyName; questionToken?: Node; initializer: Expression; } @@ -460,9 +483,16 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } + interface PropertyLikeDeclaration extends Declaration { + name: PropertyName; + } interface BindingPattern extends Node { elements: NodeArray; } + interface ObjectBindingPattern extends BindingPattern { + } + interface ArrayBindingPattern extends BindingPattern { + } /** * Several node kinds share function-like features such as a signature, * a name, and a body. These nodes should extend FunctionLikeDeclaration. @@ -477,45 +507,61 @@ declare namespace ts { questionToken?: Node; body?: Block | Expression; } - interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { + interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { name?: Identifier; - body?: Block; + body?: FunctionBody; + } + interface MethodSignature extends SignatureDeclaration, TypeElement { + name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - body?: Block; + name: PropertyName; + body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { - body?: Block; + body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { _semicolonClassElementBrand: any; } interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { _accessorDeclarationBrand: any; - body: Block; + name: PropertyName; + body: FunctionBody; } - interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { + interface GetAccessorDeclaration extends AccessorDeclaration { + } + interface SetAccessorDeclaration extends AccessorDeclaration { + } + interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { _indexSignatureDeclarationBrand: any; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface ThisTypeNode extends TypeNode { + _thisTypeNodeBrand: any; + } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { _functionOrConstructorTypeNodeBrand: any; } + interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + } + interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + } interface TypeReferenceNode extends TypeNode { typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { - parameterName: Identifier; + parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { - members: NodeArray; + members: NodeArray; } interface ArrayTypeNode extends TypeNode { elementType: TypeNode; @@ -533,13 +579,18 @@ declare namespace ts { interface ParenthesizedTypeNode extends TypeNode { type: TypeNode; } - interface StringLiteral extends LiteralExpression, TypeNode { + interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode { + _stringLiteralTypeBrand: any; + } + interface StringLiteral extends LiteralExpression { _stringLiteralBrand: any; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } + interface OmittedExpression extends Expression { + } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; } @@ -594,25 +645,34 @@ declare namespace ts { colonToken: Node; whenFalse: Expression; } + type FunctionBody = Block; + type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { name?: Identifier; - body: Block | Expression; + body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { equalsGreaterThanToken: Node; + body: ConciseBody; } - interface LiteralExpression extends PrimaryExpression { + interface LiteralLikeNode extends Node { text: string; isUnterminated?: boolean; hasExtendedUnicodeEscape?: boolean; } + interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { + _literalExpressionBrand: any; + } + interface TemplateLiteralFragment extends LiteralLikeNode { + _templateLiteralFragmentBrand: any; + } interface TemplateExpression extends PrimaryExpression { - head: LiteralExpression; + head: TemplateLiteralFragment; templateSpans: NodeArray; } interface TemplateSpan extends Node { expression: Expression; - literal: LiteralExpression; + literal: TemplateLiteralFragment; } interface ParenthesizedExpression extends PrimaryExpression { expression: Expression; @@ -694,6 +754,14 @@ declare namespace ts { interface Statement extends Node { _statementBrand: any; } + interface EmptyStatement extends Statement { + } + interface DebuggerStatement extends Statement { + } + interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + name?: Identifier; + } + type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { statements: NodeArray; } @@ -730,9 +798,13 @@ declare namespace ts { initializer: VariableDeclarationList | Expression; expression: Expression; } - interface BreakOrContinueStatement extends Statement { + interface BreakStatement extends Statement { label?: Identifier; } + interface ContinueStatement extends Statement { + label?: Identifier; + } + type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { expression?: Expression; } @@ -748,7 +820,7 @@ declare namespace ts { clauses: NodeArray; } interface CaseClause extends Node { - expression?: Expression; + expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { @@ -777,24 +849,31 @@ declare namespace ts { heritageClauses?: NodeArray; members: NodeArray; } - interface ClassDeclaration extends ClassLikeDeclaration, Statement { + interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { } interface ClassElement extends Declaration { _classElementBrand: any; + name?: PropertyName; } - interface InterfaceDeclaration extends Declaration, Statement { + interface TypeElement extends Declaration { + _typeElementBrand: any; + name?: PropertyName; + questionToken?: Node; + } + interface InterfaceDeclaration extends DeclarationStatement { name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; - members: NodeArray; + members: NodeArray; } interface HeritageClause extends Node { token: SyntaxKind; types?: NodeArray; } - interface TypeAliasDeclaration extends Declaration, Statement { + interface TypeAliasDeclaration extends DeclarationStatement { name: Identifier; typeParameters?: NodeArray; type: TypeNode; @@ -803,18 +882,19 @@ declare namespace ts { name: DeclarationName; initializer?: Expression; } - interface EnumDeclaration extends Declaration, Statement { + interface EnumDeclaration extends DeclarationStatement { name: Identifier; members: NodeArray; } - interface ModuleDeclaration extends Declaration, Statement { + type ModuleBody = ModuleBlock | ModuleDeclaration; + interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; body: ModuleBlock | ModuleDeclaration; } interface ModuleBlock extends Node, Statement { statements: NodeArray; } - interface ImportEqualsDeclaration extends Declaration, Statement { + interface ImportEqualsDeclaration extends DeclarationStatement { name: Identifier; moduleReference: EntityName | ExternalModuleReference; } @@ -832,22 +912,27 @@ declare namespace ts { interface NamespaceImport extends Declaration { name: Identifier; } - interface ExportDeclaration extends Declaration, Statement { + interface ExportDeclaration extends DeclarationStatement { exportClause?: NamedExports; moduleSpecifier?: Expression; } - interface NamedImportsOrExports extends Node { - elements: NodeArray; + interface NamedImports extends Node { + elements: NodeArray; } - type NamedImports = NamedImportsOrExports; - type NamedExports = NamedImportsOrExports; - interface ImportOrExportSpecifier extends Declaration { + interface NamedExports extends Node { + elements: NodeArray; + } + type NamedImportsOrExports = NamedImports | NamedExports; + interface ImportSpecifier extends Declaration { propertyName?: Identifier; name: Identifier; } - type ImportSpecifier = ImportOrExportSpecifier; - type ExportSpecifier = ImportOrExportSpecifier; - interface ExportAssignment extends Declaration, Statement { + interface ExportSpecifier extends Declaration { + propertyName?: Identifier; + name: Identifier; + } + type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; + interface ExportAssignment extends DeclarationStatement { isExportEquals?: boolean; expression: Expression; } @@ -908,7 +993,7 @@ declare namespace ts { interface JSDocThisType extends JSDocType { type: JSDocType; } - interface JSDocRecordMember extends PropertyDeclaration { + interface JSDocRecordMember extends PropertySignature { name: Identifier | LiteralExpression; type?: JSDocType; } @@ -934,16 +1019,17 @@ declare namespace ts { postParameterName?: Identifier; isBracketed: boolean; } + interface AmdDependency { + path: string; + name: string; + } interface SourceFile extends Declaration { statements: NodeArray; endOfFileToken: Node; fileName: string; path: Path; text: string; - amdDependencies: { - path: string; - name: string; - }[]; + amdDependencies: AmdDependency[]; moduleName: string; referencedFiles: FileReference[]; languageVariant: LanguageVariant; @@ -1053,6 +1139,7 @@ declare namespace ts { getReturnTypeOfSignature(signature: Signature): Type; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol; + getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; getShorthandAssignmentValueSymbol(location: Node): Symbol; getTypeAtLocation(node: Node): Type; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; @@ -1078,7 +1165,7 @@ declare namespace ts { interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; @@ -1117,10 +1204,20 @@ declare namespace ts { WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, } + enum TypePredicateKind { + This = 0, + Identifier = 1, + } interface TypePredicate { + kind: TypePredicateKind; + type: Type; + } + interface ThisTypePredicate extends TypePredicate { + _thisTypePredicateBrand: any; + } + interface IdentifierTypePredicate extends TypePredicate { parameterName: string; parameterIndex: number; - type: Type; } enum SymbolFlags { None = 0, @@ -1222,6 +1319,7 @@ declare namespace ts { ESSymbol = 16777216, ThisType = 33554432, ObjectLiteralPatternWithComputedProperties = 67108864, + PredicateType = 134217728, StringLike = 258, NumberLike = 132, ObjectType = 80896, @@ -1234,6 +1332,9 @@ declare namespace ts { symbol?: Symbol; pattern?: DestructuringPattern; } + interface PredicateType extends Type { + predicate: ThisTypePredicate | IdentifierTypePredicate; + } interface StringLiteralType extends Type { text: string; } @@ -1279,7 +1380,6 @@ declare namespace ts { declaration: SignatureDeclaration; typeParameters: TypeParameter[]; parameters: Symbol[]; - typePredicate?: TypePredicate; } enum IndexKind { String = 0, @@ -1331,6 +1431,7 @@ declare namespace ts { inlineSourceMap?: boolean; inlineSources?: boolean; jsx?: JsxEmit; + reactNamespace?: string; listFiles?: boolean; locale?: string; mapRoot?: string; @@ -1366,6 +1467,8 @@ declare namespace ts { noImplicitReturns?: boolean; noFallthroughCasesInSwitch?: boolean; forceConsistentCasingInFileNames?: boolean; + allowSyntheticDefaultImports?: boolean; + allowJs?: boolean; [option: string]: string | number | boolean; } enum ModuleKind { @@ -1409,6 +1512,7 @@ declare namespace ts { interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string; + directoryExists?(directoryName: string): boolean; } interface ResolvedModule { resolvedFileName: string; @@ -1537,6 +1641,7 @@ declare namespace ts { */ function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; + function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -1546,10 +1651,10 @@ declare namespace ts { } declare namespace ts { const version: string; - function findConfigFile(searchPath: string): string; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1582,7 +1687,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -1590,7 +1695,7 @@ declare namespace ts { } declare namespace ts { /** The version of the language service API */ - let servicesVersion: string; + const servicesVersion: string; interface Node { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; @@ -1659,7 +1764,7 @@ declare namespace ts { /** Releases all resources held by this script snapshot */ dispose?(): void; } - module ScriptSnapshot { + namespace ScriptSnapshot { function fromString(text: string): IScriptSnapshot; } interface PreProcessedFileInfo { @@ -1687,6 +1792,7 @@ declare namespace ts { error?(s: string): void; useCaseSensitiveFileNames?(): boolean; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + directoryExists?(directoryName: string): boolean; } interface LanguageService { cleanupSemanticCache(): void; @@ -1782,7 +1888,7 @@ declare namespace ts { fileName: string; highlightSpans: HighlightSpan[]; } - module HighlightSpanKind { + namespace HighlightSpanKind { const none: string; const definition: string; const reference: string; @@ -1824,6 +1930,7 @@ declare namespace ts { InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; [s: string]: boolean | number | string; @@ -2068,7 +2175,7 @@ declare namespace ts { releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; reportStats(): string; } - module ScriptElementKind { + namespace ScriptElementKind { const unknown: string; const warning: string; const keyword: string; @@ -2099,7 +2206,7 @@ declare namespace ts { const constElement: string; const letElement: string; } - module ScriptElementKindModifier { + namespace ScriptElementKindModifier { const none: string; const publicMemberModifier: string; const privateMemberModifier: string; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 498ddc37860..1e2f51f5aae 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -195,133 +195,135 @@ var ts; SyntaxKind[SyntaxKind["UnionType"] = 158] = "UnionType"; SyntaxKind[SyntaxKind["IntersectionType"] = 159] = "IntersectionType"; SyntaxKind[SyntaxKind["ParenthesizedType"] = 160] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 161] = "ThisType"; + SyntaxKind[SyntaxKind["StringLiteralType"] = 162] = "StringLiteralType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 161] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 162] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 163] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 163] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 164] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 165] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 164] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 165] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 166] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 167] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 168] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 169] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 170] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 171] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 172] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 173] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 174] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 175] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 176] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 177] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 178] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 179] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 180] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 181] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 182] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 183] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 184] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElementExpression"] = 185] = "SpreadElementExpression"; - SyntaxKind[SyntaxKind["ClassExpression"] = 186] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 187] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 188] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 189] = "AsExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 166] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 167] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 168] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 169] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 170] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 171] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 172] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 173] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 174] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 175] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 176] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 177] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 178] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 179] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 180] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 181] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 182] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 183] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 184] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 185] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 186] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElementExpression"] = 187] = "SpreadElementExpression"; + SyntaxKind[SyntaxKind["ClassExpression"] = 188] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 189] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 190] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 191] = "AsExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 190] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 191] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 192] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 193] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 192] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 193] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 194] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 195] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 196] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 197] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 198] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 199] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 200] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 201] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 202] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 203] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 204] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 205] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 206] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 207] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 208] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 209] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 210] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 211] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 212] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 213] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 214] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 215] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 216] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 217] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 218] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 219] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 220] = "CaseBlock"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 221] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 222] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 223] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 224] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 225] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 226] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 227] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 228] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 229] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 230] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 231] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 194] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 195] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 196] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 197] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 198] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 199] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 200] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 201] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 202] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 203] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 204] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 205] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 206] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 207] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 208] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 209] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 210] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 211] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 212] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 213] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 214] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 215] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 216] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 217] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 218] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 219] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 220] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 221] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 222] = "CaseBlock"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 223] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 224] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 225] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 226] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 227] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 228] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 229] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 230] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 231] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 232] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 233] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 232] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 234] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 233] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 234] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 235] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxText"] = 236] = "JsxText"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 237] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 238] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 239] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 240] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 235] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 236] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 237] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxText"] = 238] = "JsxText"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 239] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 240] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 241] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 242] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 241] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 242] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 243] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 244] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 243] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 244] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 245] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 246] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 245] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 246] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 247] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 248] = "ShorthandPropertyAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 247] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 249] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 248] = "SourceFile"; + SyntaxKind[SyntaxKind["SourceFile"] = 250] = "SourceFile"; // JSDoc nodes. - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 249] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 251] = "JSDocTypeExpression"; // The * type. - SyntaxKind[SyntaxKind["JSDocAllType"] = 250] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 252] = "JSDocAllType"; // The ? type. - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 251] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocArrayType"] = 252] = "JSDocArrayType"; - SyntaxKind[SyntaxKind["JSDocUnionType"] = 253] = "JSDocUnionType"; - SyntaxKind[SyntaxKind["JSDocTupleType"] = 254] = "JSDocTupleType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 255] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 256] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocRecordType"] = 257] = "JSDocRecordType"; - SyntaxKind[SyntaxKind["JSDocRecordMember"] = 258] = "JSDocRecordMember"; - SyntaxKind[SyntaxKind["JSDocTypeReference"] = 259] = "JSDocTypeReference"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 260] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 261] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 262] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocConstructorType"] = 263] = "JSDocConstructorType"; - SyntaxKind[SyntaxKind["JSDocThisType"] = 264] = "JSDocThisType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 265] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 266] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 267] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 268] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 269] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 270] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 253] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 254] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 255] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 256] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 257] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 258] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 259] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 260] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 261] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 262] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 263] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 264] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 265] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 266] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 267] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 268] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 269] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 270] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 271] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 272] = "JSDocTemplateTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 271] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 273] = "SyntaxList"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 272] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 274] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; @@ -331,8 +333,8 @@ var ts; SyntaxKind[SyntaxKind["LastKeyword"] = 134] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 106] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 114] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 151] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 160] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 150] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 162] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 15] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 68] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; @@ -408,10 +410,14 @@ var ts; var ParserContextFlags = ts.ParserContextFlags; (function (JsxFlags) { JsxFlags[JsxFlags["None"] = 0] = "None"; + /** An element from a named property of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; - JsxFlags[JsxFlags["ClassElement"] = 4] = "ClassElement"; - JsxFlags[JsxFlags["UnknownElement"] = 8] = "UnknownElement"; + /** An element backed by a class, class-like, or function value */ + JsxFlags[JsxFlags["ValueElement"] = 4] = "ValueElement"; + /** Element resolution failed */ + JsxFlags[JsxFlags["UnknownElement"] = 16] = "UnknownElement"; JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; })(ts.JsxFlags || (ts.JsxFlags = {})); var JsxFlags = ts.JsxFlags; @@ -426,7 +432,7 @@ var ts; function OperationCanceledException() { } return OperationCanceledException; - })(); + }()); ts.OperationCanceledException = OperationCanceledException; /** Return code used by getEmitOutput function to indicate status of the function */ (function (ExitStatus) { @@ -472,6 +478,11 @@ var ts; SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; })(ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); var SymbolAccessibility = ts.SymbolAccessibility; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(ts.TypePredicateKind || (ts.TypePredicateKind = {})); + var TypePredicateKind = ts.TypePredicateKind; /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator * metadata */ /* @internal */ @@ -623,6 +634,7 @@ var ts; TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol"; TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType"; TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 67108864] = "ObjectLiteralPatternWithComputedProperties"; + TypeFlags[TypeFlags["PredicateType"] = 134217728] = "PredicateType"; /* @internal */ TypeFlags[TypeFlags["Intrinsic"] = 16777343] = "Intrinsic"; /* @internal */ @@ -633,7 +645,7 @@ var ts; TypeFlags[TypeFlags["UnionOrIntersection"] = 49152] = "UnionOrIntersection"; TypeFlags[TypeFlags["StructuredType"] = 130048] = "StructuredType"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; + TypeFlags[TypeFlags["RequiresWidening"] = 140509184] = "RequiresWidening"; /* @internal */ TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; })(ts.TypeFlags || (ts.TypeFlags = {})); @@ -648,6 +660,19 @@ var ts; IndexKind[IndexKind["Number"] = 1] = "Number"; })(ts.IndexKind || (ts.IndexKind = {})); var IndexKind = ts.IndexKind; + /* @internal */ + (function (SpecialPropertyAssignmentKind) { + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + /// exports.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + /// module.exports = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + /// className.prototype.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + /// this.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + })(ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + var SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; @@ -1068,9 +1093,11 @@ var ts; var count = array.length; if (count > 0) { var pos = 0; - var result = arguments.length <= 2 ? array[pos++] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos++; while (pos < count) { - result = f(result, array[pos++]); + result = f(result, array[pos]); + pos++; } return result; } @@ -1082,9 +1109,11 @@ var ts; if (array) { var pos = array.length - 1; if (pos >= 0) { - var result = arguments.length <= 2 ? array[pos--] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos--; while (pos >= 0) { - result = f(result, array[pos--]); + result = f(result, array[pos]); + pos--; } return result; } @@ -1177,6 +1206,32 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + /** + * Reduce the properties of a map. + * + * @param map The map to reduce + * @param callback An aggregation function that is called for each entry in the map + * @param initial The initial value for the reduction. + */ + 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; + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; function memoize(callback) { var value; return function () { @@ -1502,7 +1557,7 @@ var ts; } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; function getBaseFileName(path) { - if (!path) { + if (path === undefined) { return undefined; } var i = path.lastIndexOf(ts.directorySeparator); @@ -1530,14 +1585,19 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedJsExtensions = ts.supportedExtensions.concat(".js", ".jsx"); - function isSupportedSourceFileName(fileName) { + ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedJavascriptExtensions = [".js", ".jsx"]; + var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + function getSupportedExtensions(options) { + return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + ts.getSupportedExtensions = getSupportedExtensions; + function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; } - for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; + for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -1556,22 +1616,6 @@ var ts; return path; } ts.removeFileExtension = removeFileExtension; - var backslashOrDoubleQuote = /[\"\\]/g; - var escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { - "\0": "\\0", - "\t": "\\t", - "\v": "\\v", - "\f": "\\f", - "\b": "\\b", - "\r": "\\r", - "\n": "\\n", - "\\": "\\\\", - "\"": "\\\"", - "\u2028": "\\u2028", - "\u2029": "\\u2029", - "\u0085": "\\u0085" // nextLine - }; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -1622,7 +1666,7 @@ var ts; } Debug.assert = assert; function fail(message) { - Debug.assert(false, message); + Debug.assert(/*expression*/ false, message); } Debug.fail = fail; })(Debug = ts.Debug || (ts.Debug = {})); @@ -1783,7 +1827,6 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); - var _tty = require("tty"); // average async stat takes about 30 microseconds // set chunk size to do 30 files in < 1 millisecond function createWatchedFileSet(interval, chunkSize) { @@ -1858,7 +1901,7 @@ var ts; // REVIEW: for now this implementation uses polling. // The advantage of polling is that it works reliably // on all os and with network mounted files. - // For 90 referenced files, the average time to detect + // For 90 referenced files, the average time to detect // changes is 2*msInterval (by default 5 seconds). // The overhead of this is .04 percent (1/2500) with // average pause of < 1 millisecond (and max @@ -1869,9 +1912,6 @@ var ts; // to increase the chunk size or decrease the interval // time dynamically to match the large reference set? var watchedFileSet = createWatchedFileSet(); - function isNode4OrLater() { - return parseInt(process.version.charAt(1)) >= 4; - } var platform = _os.platform(); // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; @@ -1965,17 +2005,13 @@ var ts; // and is more efficient than `fs.watchFile` (ref: https://github.com/nodejs/node/pull/2649 // and https://github.com/Microsoft/TypeScript/issues/4643), therefore // if the current node.js version is newer than 4, use `fs.watch` instead. - if (isNode4OrLater()) { - // Note: in node the callback of fs.watch is given only the relative file name as a parameter - return _fs.watch(fileName, function (eventName, relativeFileName) { return callback(fileName); }); - } var watchedFile = watchedFileSet.addFile(fileName, callback); return { close: function () { return watchedFileSet.removeFile(watchedFile); } }; }, watchDirectory: function (path, callback, recursive) { - // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) return _fs.watch(path, { persistent: true, recursive: !!recursive }, function (eventName, relativeFileName) { // In watchDirectory we only care about adding and removing files (when event name is @@ -2020,6 +2056,33 @@ var ts; } }; } + function getChakraSystem() { + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, encoding) { + // encoding is automatically handled by the implementation in ChakraHost + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = "\uFEFF" + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + readDirectory: ChakraHost.readDirectory, + exit: ChakraHost.quit + }; + } if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { return getWScriptSystem(); } @@ -2028,6 +2091,9 @@ var ts; // process.browser check excludes webpack and browserify return getNodeSystem(); } + else if (typeof ChakraHost !== "undefined") { + return getChakraSystem(); + } else { return undefined; // Unsupported host } @@ -2148,7 +2214,7 @@ var ts; Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: ts.DiagnosticCategory.Error, key: "Modifiers_not_permitted_on_index_signature_members_1145", message: "Modifiers not permitted on index signature members." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_1148", message: "Cannot compile modules unless the '--module' flag is provided." }, + Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_optio_1148", message: "Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -2235,6 +2301,10 @@ var ts; _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, + An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, + A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, + A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, @@ -2248,11 +2318,12 @@ var ts; Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list_2313", message: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." }, + Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, @@ -2262,6 +2333,7 @@ var ts; Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, + Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, @@ -2332,6 +2404,7 @@ var ts; Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, + Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, @@ -2445,6 +2518,8 @@ var ts; Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, + A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_return_type_positions_for_functions_and_methods: { code: 2519, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_r_2519", message: "A 'this'-based type predicate is only allowed within a class or interface's members, get accessors, or return type positions for functions and methods." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, @@ -2454,7 +2529,7 @@ var ts; A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_must_be_an_object_type_2600", message: "JSX element attributes type '{0}' must be an object type." }, + 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." }, Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'" }, @@ -2470,6 +2545,9 @@ var ts; Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element" }, + Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'" }, + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, 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}'." }, @@ -2554,6 +2632,11 @@ var ts; Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, + Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'" }, + The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'" }, + Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalide value for '--reactNamespace'. '{0}' is not a valid identifier." }, 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." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -2564,6 +2647,7 @@ var ts; Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -2619,6 +2703,8 @@ var ts; Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, + Allow_javascript_files_to_be_compiled: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6083", message: "Allow javascript files to be compiled." }, + Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit_6084", message: "Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit" }, 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." }, @@ -2666,7 +2752,8 @@ var ts; Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'" }, An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." } + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, + JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." } }; })(ts || (ts = {})); /// @@ -2906,7 +2993,8 @@ var ts; var pos = 0; var lineStart = 0; while (pos < text.length) { - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 13 /* carriageReturn */: if (text.charCodeAt(pos) === 10 /* lineFeed */) { @@ -3040,6 +3128,11 @@ var ts; ts.couldStartTrivia = couldStartTrivia; /* @internal */ function skipTrivia(text, pos, stopAfterLineBreak) { + // Using ! with a greater than test is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + if (!(pos >= 0)) { + return pos; + } // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -3276,6 +3369,19 @@ var ts; ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; + /* @internal */ + function isIdentifier(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1, n = name.length; i < n; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifier = isIdentifier; // Creates a scanner over a (possibly unspecified) range of a piece of text. function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } @@ -3398,7 +3504,8 @@ var ts; return value; } function scanString() { - var quote = text.charCodeAt(pos++); + var quote = text.charCodeAt(pos); + pos++; var result = ""; var start = pos; while (true) { @@ -3494,7 +3601,8 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); return ""; } - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 48 /* _0 */: return "\0"; @@ -3721,7 +3829,8 @@ var ts; } return pos += 2, token = 31 /* ExclamationEqualsToken */; } - return pos++, token = 49 /* ExclamationToken */; + pos++; + return token = 49 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); @@ -3732,7 +3841,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 62 /* PercentEqualsToken */; } - return pos++, token = 40 /* PercentToken */; + pos++; + return token = 40 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { return pos += 2, token = 51 /* AmpersandAmpersandToken */; @@ -3740,11 +3850,14 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 66 /* AmpersandEqualsToken */; } - return pos++, token = 46 /* AmpersandToken */; + pos++; + return token = 46 /* AmpersandToken */; case 40 /* openParen */: - return pos++, token = 17 /* OpenParenToken */; + pos++; + return token = 17 /* OpenParenToken */; case 41 /* closeParen */: - return pos++, token = 18 /* CloseParenToken */; + pos++; + return token = 18 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 59 /* AsteriskEqualsToken */; @@ -3755,7 +3868,8 @@ var ts; } return pos += 2, token = 38 /* AsteriskAsteriskToken */; } - return pos++, token = 37 /* AsteriskToken */; + pos++; + return token = 37 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { return pos += 2, token = 41 /* PlusPlusToken */; @@ -3763,9 +3877,11 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 57 /* PlusEqualsToken */; } - return pos++, token = 35 /* PlusToken */; + pos++; + return token = 35 /* PlusToken */; case 44 /* comma */: - return pos++, token = 24 /* CommaToken */; + pos++; + return token = 24 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { return pos += 2, token = 42 /* MinusMinusToken */; @@ -3773,7 +3889,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 58 /* MinusEqualsToken */; } - return pos++, token = 36 /* MinusToken */; + pos++; + return token = 36 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { tokenValue = scanNumber(); @@ -3782,7 +3899,8 @@ var ts; if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { return pos += 3, token = 22 /* DotDotDotToken */; } - return pos++, token = 21 /* DotToken */; + pos++; + return token = 21 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -3830,7 +3948,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 61 /* SlashEqualsToken */; } - return pos++, token = 39 /* SlashToken */; + pos++; + return token = 39 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; @@ -3882,9 +4001,11 @@ var ts; tokenValue = scanNumber(); return token = 8 /* NumericLiteral */; case 58 /* colon */: - return pos++, token = 54 /* ColonToken */; + pos++; + return token = 54 /* ColonToken */; case 59 /* semicolon */: - return pos++, token = 23 /* SemicolonToken */; + pos++; + return token = 23 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3909,7 +4030,8 @@ var ts; text.charCodeAt(pos + 2) !== 42 /* asterisk */) { return pos += 2, token = 26 /* LessThanSlashToken */; } - return pos++, token = 25 /* LessThanToken */; + pos++; + return token = 25 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3929,7 +4051,8 @@ var ts; if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { return pos += 2, token = 34 /* EqualsGreaterThanToken */; } - return pos++, token = 56 /* EqualsToken */; + pos++; + return token = 56 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3940,20 +4063,26 @@ var ts; return token = 7 /* ConflictMarkerTrivia */; } } - return pos++, token = 27 /* GreaterThanToken */; + pos++; + return token = 27 /* GreaterThanToken */; case 63 /* question */: - return pos++, token = 53 /* QuestionToken */; + pos++; + return token = 53 /* QuestionToken */; case 91 /* openBracket */: - return pos++, token = 19 /* OpenBracketToken */; + pos++; + return token = 19 /* OpenBracketToken */; case 93 /* closeBracket */: - return pos++, token = 20 /* CloseBracketToken */; + pos++; + return token = 20 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 68 /* CaretEqualsToken */; } - return pos++, token = 48 /* CaretToken */; + pos++; + return token = 48 /* CaretToken */; case 123 /* openBrace */: - return pos++, token = 15 /* OpenBraceToken */; + pos++; + return token = 15 /* OpenBraceToken */; case 124 /* bar */: if (text.charCodeAt(pos + 1) === 124 /* bar */) { return pos += 2, token = 52 /* BarBarToken */; @@ -3961,13 +4090,17 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 67 /* BarEqualsToken */; } - return pos++, token = 47 /* BarToken */; + pos++; + return token = 47 /* BarToken */; case 125 /* closeBrace */: - return pos++, token = 16 /* CloseBraceToken */; + pos++; + return token = 16 /* CloseBraceToken */; case 126 /* tilde */: - return pos++, token = 50 /* TildeToken */; + pos++; + return token = 50 /* TildeToken */; case 64 /* at */: - return pos++, token = 55 /* AtToken */; + pos++; + return token = 55 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -3976,7 +4109,8 @@ var ts; return token = getIdentifierToken(); } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0 /* Unknown */; + pos++; + return token = 0 /* Unknown */; default: if (isIdentifierStart(ch, languageVersion)) { pos++; @@ -3998,7 +4132,8 @@ var ts; continue; } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0 /* Unknown */; + pos++; + return token = 0 /* Unknown */; } } } @@ -4014,10 +4149,12 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 64 /* GreaterThanGreaterThanEqualsToken */; } - return pos++, token = 44 /* GreaterThanGreaterThanToken */; + pos++; + return token = 44 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { - return pos++, token = 29 /* GreaterThanEqualsToken */; + pos++; + return token = 29 /* GreaterThanEqualsToken */; } } return token; @@ -4109,7 +4246,7 @@ var ts; break; } } - return token = 236 /* JsxText */; + return token = 238 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -4150,10 +4287,10 @@ var ts; return result; } function lookAhead(callback) { - return speculationHelper(callback, /*isLookahead:*/ true); + return speculationHelper(callback, /*isLookahead*/ true); } function tryScan(callback) { - return speculationHelper(callback, /*isLookahead:*/ false); + return speculationHelper(callback, /*isLookahead*/ false); } function setText(newText, start, length) { text = newText || ""; @@ -4244,7 +4381,7 @@ var ts; if (array1.length !== array2.length) { return false; } - for (var i = 0; i < array1.length; ++i) { + for (var i = 0; i < array1.length; i++) { var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; if (!equals) { return false; @@ -4292,7 +4429,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 248 /* SourceFile */) { + while (node && node.kind !== 250 /* SourceFile */) { node = node.parent; } return node; @@ -4404,15 +4541,15 @@ var ts; return current; } switch (current.kind) { - case 248 /* SourceFile */: - case 220 /* CaseBlock */: - case 244 /* CatchClause */: - case 218 /* ModuleDeclaration */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 250 /* SourceFile */: + case 222 /* CaseBlock */: + case 246 /* CatchClause */: + case 220 /* ModuleDeclaration */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: return current; - case 192 /* Block */: + case 194 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block if (!isFunctionLike(current.parent)) { @@ -4425,9 +4562,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 211 /* VariableDeclaration */ && + declaration.kind === 213 /* VariableDeclaration */ && declaration.parent && - declaration.parent.kind === 244 /* CatchClause */; + declaration.parent.kind === 246 /* CatchClause */; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; // Return display name of an identifier @@ -4466,7 +4603,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -4475,16 +4612,17 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 217 /* InterfaceDeclaration */: + case 220 /* ModuleDeclaration */: + case 219 /* EnumDeclaration */: + case 249 /* EnumMember */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 143 /* MethodDeclaration */: errorNode = node.name; break; } @@ -4512,11 +4650,11 @@ var ts; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 217 /* EnumDeclaration */ && isConst(node); + return node.kind === 219 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 163 /* BindingElement */ || isBindingPattern(node))) { + while (node && (node.kind === 165 /* BindingElement */ || isBindingPattern(node))) { node = node.parent; } return node; @@ -4531,14 +4669,14 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 211 /* VariableDeclaration */) { + if (node.kind === 213 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 212 /* VariableDeclarationList */) { + if (node && node.kind === 214 /* VariableDeclarationList */) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 193 /* VariableStatement */) { + if (node && node.kind === 195 /* VariableStatement */) { flags |= node.flags; } return flags; @@ -4553,7 +4691,7 @@ var ts; } ts.isLet = isLet; function isPrologueDirective(node) { - return node.kind === 195 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; + return node.kind === 197 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { @@ -4584,7 +4722,7 @@ var ts; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isTypeNode(node) { - if (151 /* FirstTypeNode */ <= node.kind && node.kind <= 160 /* LastTypeNode */) { + if (150 /* FirstTypeNode */ <= node.kind && node.kind <= 162 /* LastTypeNode */) { return true; } switch (node.kind) { @@ -4595,11 +4733,8 @@ var ts; case 131 /* SymbolKeyword */: return true; case 103 /* VoidKeyword */: - return node.parent.kind !== 177 /* VoidExpression */; - case 9 /* StringLiteral */: - // Specialized signatures can have string literals as their parameters' type names - return node.parent.kind === 138 /* Parameter */; - case 188 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 179 /* VoidExpression */; + case 190 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container @@ -4608,13 +4743,13 @@ var ts; if (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 168 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 168 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); case 135 /* QualifiedName */: - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: case 97 /* ThisKeyword */: var parent_1 = node.parent; if (parent_1.kind === 154 /* TypeQuery */) { @@ -4626,22 +4761,22 @@ var ts; // // Calling isTypeNode would consider the qualified name A.B a type node. Only C or // A.B.C is a type node. - if (151 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 160 /* LastTypeNode */) { + if (150 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 162 /* LastTypeNode */) { return true; } switch (parent_1.kind) { - case 188 /* ExpressionWithTypeArguments */: + case 190 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); case 137 /* TypeParameter */: return node === parent_1.constraint; case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 138 /* Parameter */: - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: return node === parent_1.type; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: case 144 /* Constructor */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: @@ -4652,12 +4787,12 @@ var ts; case 148 /* ConstructSignature */: case 149 /* IndexSignature */: return node === parent_1.type; - case 171 /* TypeAssertionExpression */: + case 173 /* TypeAssertionExpression */: return node === parent_1.type; - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 170 /* TaggedTemplateExpression */: + case 172 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -4671,23 +4806,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 204 /* ReturnStatement */: + case 206 /* ReturnStatement */: return visitor(node); - case 220 /* CaseBlock */: - case 192 /* Block */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: + case 222 /* CaseBlock */: + case 194 /* Block */: + case 198 /* IfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 207 /* WithStatement */: + case 208 /* SwitchStatement */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: + case 209 /* LabeledStatement */: + case 211 /* TryStatement */: + case 246 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -4697,18 +4832,18 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 184 /* YieldExpression */: + case 186 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 219 /* EnumDeclaration */: + case 217 /* InterfaceDeclaration */: + case 220 /* ModuleDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. @@ -4735,14 +4870,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 163 /* BindingElement */: - case 247 /* EnumMember */: + case 165 /* BindingElement */: + case 249 /* EnumMember */: case 138 /* Parameter */: - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 246 /* ShorthandPropertyAssignment */: - case 211 /* VariableDeclaration */: + case 248 /* ShorthandPropertyAssignment */: + case 213 /* VariableDeclaration */: return true; } } @@ -4754,7 +4889,7 @@ var ts; } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 214 /* ClassDeclaration */ || node.kind === 186 /* ClassExpression */); + return node && (node.kind === 216 /* ClassDeclaration */ || node.kind === 188 /* ClassExpression */); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -4764,9 +4899,9 @@ var ts; function isFunctionLikeKind(kind) { switch (kind) { case 144 /* Constructor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 176 /* ArrowFunction */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: @@ -4787,8 +4922,8 @@ var ts; case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: return true; } return false; @@ -4796,26 +4931,30 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: return true; - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 192 /* Block */ && isFunctionLike(node.parent); + return node && node.kind === 194 /* Block */ && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 143 /* MethodDeclaration */ && node.parent.kind === 165 /* ObjectLiteralExpression */; + return node && node.kind === 143 /* MethodDeclaration */ && node.parent.kind === 167 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1 /* Identifier */; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; function getContainingFunction(node) { while (true) { node = node.parent; @@ -4869,14 +5008,14 @@ var ts; node = node.parent; } break; - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // Fall through - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 218 /* ModuleDeclaration */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 220 /* ModuleDeclaration */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 143 /* MethodDeclaration */: @@ -4887,34 +5026,45 @@ var ts; case 147 /* CallSignature */: case 148 /* ConstructSignature */: case 149 /* IndexSignature */: - case 217 /* EnumDeclaration */: - case 248 /* SourceFile */: + case 219 /* EnumDeclaration */: + case 250 /* SourceFile */: return node; } } } ts.getThisContainer = getThisContainer; - function getSuperContainer(node, includeFunctions) { + /** + * Given an super call\property node returns a closest node where either + * - super call\property is legal in the node and not legal in the parent node the node. + * i.e. super call is legal in constructor but not legal in the class body. + * - node is arrow function (so caller might need to call getSuperContainer in case if he needs to climb higher) + * - super call\property is definitely illegal in the node (but might be legal in some subnode) + * i.e. super property access is illegal in function declaration but can be legal in the statement list + */ + function getSuperContainer(node, stopOnFunctions) { while (true) { node = node.parent; - if (!node) + if (!node) { return node; + } switch (node.kind) { case 136 /* ComputedPropertyName */: - // If the grandparent node is an object literal (as opposed to a class), - // then the computed property is not a 'super' container. - // A computed property name in a class needs to be a super container - // so that we can error on it. - if (isClassLike(node.parent.parent)) { - return node; - } - // If this is a computed property, then the parent should not - // make it a super container. The parent might be a property - // in an object literal, like a method or accessor. But in order for - // such a parent to be a super container, the reference must be in - // the *body* of the container. node = node.parent; break; + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + if (!stopOnFunctions) { + continue; + } + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + return node; case 139 /* Decorator */: // Decorators are always applied outside of the body of a class or method. if (node.parent.kind === 138 /* Parameter */ && isClassElement(node.parent.parent)) { @@ -4928,20 +5078,6 @@ var ts; node = node.parent; } break; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - if (!includeFunctions) { - continue; - } - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - return node; } } } @@ -4951,7 +5087,7 @@ var ts; switch (node.kind) { case 151 /* TypeReference */: return node.typeName; - case 188 /* ExpressionWithTypeArguments */: + case 190 /* ExpressionWithTypeArguments */: return node.expression; case 69 /* Identifier */: case 135 /* QualifiedName */: @@ -4962,7 +5098,7 @@ var ts; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 172 /* TaggedTemplateExpression */) { return node.tag; } // Will either be a CallExpression, NewExpression, or Decorator. @@ -4971,27 +5107,27 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: // classes are valid targets return true; case 141 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return node.parent.kind === 214 /* ClassDeclaration */; + return node.parent.kind === 216 /* ClassDeclaration */; case 138 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; - return node.parent.body && node.parent.parent.kind === 214 /* ClassDeclaration */; + return node.parent.body && node.parent.parent.kind === 216 /* ClassDeclaration */; case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 143 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. - return node.body && node.parent.kind === 214 /* ClassDeclaration */; + return node.body && node.parent.kind === 216 /* ClassDeclaration */; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { switch (node.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: if (node.decorators) { return true; } @@ -5017,27 +5153,12 @@ var ts; return false; } ts.nodeIsDecorated = nodeIsDecorated; - function childIsDecorated(node) { - switch (node.kind) { - case 214 /* ClassDeclaration */: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 143 /* MethodDeclaration */: - case 146 /* SetAccessor */: - return ts.forEach(node.parameters, nodeIsDecorated); - } - return false; - } - ts.childIsDecorated = childIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); - } - ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function isPropertyAccessExpression(node) { - return node.kind === 166 /* PropertyAccessExpression */; + return node.kind === 168 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 167 /* ElementAccessExpression */; + return node.kind === 169 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isExpression(node) { @@ -5047,34 +5168,34 @@ var ts; case 99 /* TrueKeyword */: case 84 /* FalseKeyword */: case 10 /* RegularExpressionLiteral */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 170 /* TaggedTemplateExpression */: - case 189 /* AsExpression */: - case 171 /* TypeAssertionExpression */: - case 172 /* ParenthesizedExpression */: - case 173 /* FunctionExpression */: - case 186 /* ClassExpression */: - case 174 /* ArrowFunction */: - case 177 /* VoidExpression */: - case 175 /* DeleteExpression */: - case 176 /* TypeOfExpression */: - case 179 /* PrefixUnaryExpression */: - case 180 /* PostfixUnaryExpression */: - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 183 /* TemplateExpression */: + case 166 /* ArrayLiteralExpression */: + case 167 /* ObjectLiteralExpression */: + case 168 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: + case 172 /* TaggedTemplateExpression */: + case 191 /* AsExpression */: + case 173 /* TypeAssertionExpression */: + case 174 /* ParenthesizedExpression */: + case 175 /* FunctionExpression */: + case 188 /* ClassExpression */: + case 176 /* ArrowFunction */: + case 179 /* VoidExpression */: + case 177 /* DeleteExpression */: + case 178 /* TypeOfExpression */: + case 181 /* PrefixUnaryExpression */: + case 182 /* PostfixUnaryExpression */: + case 183 /* BinaryExpression */: + case 184 /* ConditionalExpression */: + case 187 /* SpreadElementExpression */: + case 185 /* TemplateExpression */: case 11 /* NoSubstitutionTemplateLiteral */: - case 187 /* OmittedExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 184 /* YieldExpression */: - case 178 /* AwaitExpression */: + case 189 /* OmittedExpression */: + case 235 /* JsxElement */: + case 236 /* JsxSelfClosingElement */: + case 186 /* YieldExpression */: + case 180 /* AwaitExpression */: return true; case 135 /* QualifiedName */: while (node.parent.kind === 135 /* QualifiedName */) { @@ -5091,47 +5212,47 @@ var ts; case 97 /* ThisKeyword */: var parent_2 = node.parent; switch (parent_2.kind) { - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: case 138 /* Parameter */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 247 /* EnumMember */: - case 245 /* PropertyAssignment */: - case 163 /* BindingElement */: + case 249 /* EnumMember */: + case 247 /* PropertyAssignment */: + case 165 /* BindingElement */: return parent_2.initializer === node; - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 204 /* ReturnStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 208 /* ThrowStatement */: - case 206 /* SwitchStatement */: + case 197 /* ExpressionStatement */: + case 198 /* IfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: + case 206 /* ReturnStatement */: + case 207 /* WithStatement */: + case 208 /* SwitchStatement */: + case 243 /* CaseClause */: + case 210 /* ThrowStatement */: + case 208 /* SwitchStatement */: return parent_2.expression === node; - case 199 /* ForStatement */: + case 201 /* ForStatement */: var forStatement = parent_2; - return (forStatement.initializer === node && forStatement.initializer.kind !== 212 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 214 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: var forInStatement = parent_2; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 212 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 214 /* VariableDeclarationList */) || forInStatement.expression === node; - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 173 /* TypeAssertionExpression */: + case 191 /* AsExpression */: return node === parent_2.expression; - case 190 /* TemplateSpan */: + case 192 /* TemplateSpan */: return node === parent_2.expression; case 136 /* ComputedPropertyName */: return node === parent_2.expression; case 139 /* Decorator */: - case 240 /* JsxExpression */: - case 239 /* JsxSpreadAttribute */: + case 242 /* JsxExpression */: + case 241 /* JsxSpreadAttribute */: return true; - case 188 /* ExpressionWithTypeArguments */: + case 190 /* ExpressionWithTypeArguments */: return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: if (isExpression(parent_2)) { @@ -5155,7 +5276,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 232 /* ExternalModuleReference */; + return node.kind === 223 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 234 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -5164,7 +5285,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 232 /* ExternalModuleReference */; + return node.kind === 223 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 234 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { @@ -5182,53 +5303,59 @@ var ts; */ function isRequireCall(expression) { // of the form 'require("name")' - return expression.kind === 168 /* CallExpression */ && + return expression.kind === 170 /* CallExpression */ && expression.expression.kind === 69 /* Identifier */ && expression.expression.text === "require" && expression.arguments.length === 1 && expression.arguments[0].kind === 9 /* StringLiteral */; } ts.isRequireCall = isRequireCall; - /** - * Returns true if the node is an assignment to a property on the identifier 'exports'. - * This function does not test if the node is in a JavaScript file or not. - */ - function isExportsPropertyAssignment(expression) { - // of the form 'exports.name = expr' where 'name' and 'expr' are arbitrary - return isInJavaScriptFile(expression) && - (expression.kind === 181 /* BinaryExpression */) && - (expression.operatorToken.kind === 56 /* EqualsToken */) && - (expression.left.kind === 166 /* PropertyAccessExpression */) && - (expression.left.expression.kind === 69 /* Identifier */) && - ((expression.left.expression).text === "exports"); + /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property + /// assignments we treat as special in the binder + function getSpecialPropertyAssignmentKind(expression) { + if (expression.kind !== 183 /* BinaryExpression */) { + return 0 /* None */; + } + var expr = expression; + if (expr.operatorToken.kind !== 56 /* EqualsToken */ || expr.left.kind !== 168 /* PropertyAccessExpression */) { + return 0 /* None */; + } + var lhs = expr.left; + if (lhs.expression.kind === 69 /* Identifier */) { + var lhsId = lhs.expression; + if (lhsId.text === "exports") { + // exports.name = expr + return 1 /* ExportsProperty */; + } + else if (lhsId.text === "module" && lhs.name.text === "exports") { + // module.exports = expr + return 2 /* ModuleExports */; + } + } + else if (lhs.expression.kind === 97 /* ThisKeyword */) { + return 4 /* ThisProperty */; + } + else if (lhs.expression.kind === 168 /* PropertyAccessExpression */) { + // chained dot, e.g. x.y.z = expr; this var is the 'x.y' part + var innerPropertyAccess = lhs.expression; + if (innerPropertyAccess.expression.kind === 69 /* Identifier */ && innerPropertyAccess.name.text === "prototype") { + return 3 /* PrototypeProperty */; + } + } + return 0 /* None */; } - ts.isExportsPropertyAssignment = isExportsPropertyAssignment; - /** - * Returns true if the node is an assignment to the property access expression 'module.exports'. - * This function does not test if the node is in a JavaScript file or not. - */ - function isModuleExportsAssignment(expression) { - // of the form 'module.exports = expr' where 'expr' is arbitrary - return isInJavaScriptFile(expression) && - (expression.kind === 181 /* BinaryExpression */) && - (expression.operatorToken.kind === 56 /* EqualsToken */) && - (expression.left.kind === 166 /* PropertyAccessExpression */) && - (expression.left.expression.kind === 69 /* Identifier */) && - ((expression.left.expression).text === "module") && - (expression.left.name.text === "exports"); - } - ts.isModuleExportsAssignment = isModuleExportsAssignment; + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 222 /* ImportDeclaration */) { + if (node.kind === 224 /* ImportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 223 /* ImportEqualsDeclaration */) { var reference = node.moduleReference; - if (reference.kind === 232 /* ExternalModuleReference */) { + if (reference.kind === 234 /* ExternalModuleReference */) { return reference.expression; } } - if (node.kind === 228 /* ExportDeclaration */) { + if (node.kind === 230 /* ExportDeclaration */) { return node.moduleSpecifier; } } @@ -5239,8 +5366,8 @@ var ts; case 138 /* Parameter */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - case 246 /* ShorthandPropertyAssignment */: - case 245 /* PropertyAssignment */: + case 248 /* ShorthandPropertyAssignment */: + case 247 /* PropertyAssignment */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return node.questionToken !== undefined; @@ -5250,9 +5377,9 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 261 /* JSDocFunctionType */ && + return node.kind === 263 /* JSDocFunctionType */ && node.parameters.length > 0 && - node.parameters[0].type.kind === 263 /* JSDocConstructorType */; + node.parameters[0].type.kind === 265 /* JSDocConstructorType */; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function getJSDocTag(node, kind) { @@ -5266,15 +5393,15 @@ var ts; } } function getJSDocTypeTag(node) { - return getJSDocTag(node, 269 /* JSDocTypeTag */); + return getJSDocTag(node, 271 /* JSDocTypeTag */); } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 268 /* JSDocReturnTag */); + return getJSDocTag(node, 270 /* JSDocReturnTag */); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 270 /* JSDocTemplateTag */); + return getJSDocTag(node, 272 /* JSDocTemplateTag */); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getCorrespondingJSDocParameterTag(parameter) { @@ -5285,7 +5412,7 @@ var ts; var docComment = parameter.parent.jsDocComment; if (docComment) { return ts.forEach(docComment.tags, function (t) { - if (t.kind === 267 /* JSDocParameterTag */) { + if (t.kind === 269 /* JSDocParameterTag */) { var parameterTag = t; var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; if (name_6.text === parameterName) { @@ -5304,12 +5431,12 @@ var ts; function isRestParameter(node) { if (node) { if (node.parserContextFlags & 32 /* JavaScriptFile */) { - if (node.type && node.type.kind === 262 /* JSDocVariadicType */) { + if (node.type && node.type.kind === 264 /* JSDocVariadicType */) { return true; } var paramTag = getCorrespondingJSDocParameterTag(node); if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 262 /* JSDocVariadicType */; + return paramTag.typeExpression.type.kind === 264 /* JSDocVariadicType */; } } return node.dotDotDotToken !== undefined; @@ -5330,7 +5457,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 162 /* ArrayBindingPattern */ || node.kind === 161 /* ObjectBindingPattern */); + return !!node && (node.kind === 164 /* ArrayBindingPattern */ || node.kind === 163 /* ObjectBindingPattern */); } ts.isBindingPattern = isBindingPattern; function isNodeDescendentOf(node, ancestor) { @@ -5354,34 +5481,34 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 174 /* ArrowFunction */: - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 176 /* ArrowFunction */: + case 165 /* BindingElement */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: case 144 /* Constructor */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 230 /* ExportSpecifier */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 219 /* EnumDeclaration */: + case 249 /* EnumMember */: + case 232 /* ExportSpecifier */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 145 /* GetAccessor */: - case 223 /* ImportClause */: - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 215 /* InterfaceDeclaration */: + case 225 /* ImportClause */: + case 223 /* ImportEqualsDeclaration */: + case 228 /* ImportSpecifier */: + case 217 /* InterfaceDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - case 218 /* ModuleDeclaration */: - case 224 /* NamespaceImport */: + case 220 /* ModuleDeclaration */: + case 226 /* NamespaceImport */: case 138 /* Parameter */: - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: case 146 /* SetAccessor */: - case 246 /* ShorthandPropertyAssignment */: - case 216 /* TypeAliasDeclaration */: + case 248 /* ShorthandPropertyAssignment */: + case 218 /* TypeAliasDeclaration */: case 137 /* TypeParameter */: - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: return true; } return false; @@ -5389,25 +5516,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: - case 210 /* DebuggerStatement */: - case 197 /* DoStatement */: - case 195 /* ExpressionStatement */: - case 194 /* EmptyStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 196 /* IfStatement */: - case 207 /* LabeledStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 193 /* VariableStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 227 /* ExportAssignment */: + case 205 /* BreakStatement */: + case 204 /* ContinueStatement */: + case 212 /* DebuggerStatement */: + case 199 /* DoStatement */: + case 197 /* ExpressionStatement */: + case 196 /* EmptyStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 201 /* ForStatement */: + case 198 /* IfStatement */: + case 209 /* LabeledStatement */: + case 206 /* ReturnStatement */: + case 208 /* SwitchStatement */: + case 210 /* ThrowStatement */: + case 211 /* TryStatement */: + case 195 /* VariableStatement */: + case 200 /* WhileStatement */: + case 207 /* WithStatement */: + case 229 /* ExportAssignment */: return true; default: return false; @@ -5435,7 +5562,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 226 /* ImportSpecifier */ || parent.kind === 230 /* ExportSpecifier */) { + if (parent.kind === 228 /* ImportSpecifier */ || parent.kind === 232 /* ExportSpecifier */) { if (parent.propertyName) { return true; } @@ -5456,9 +5583,9 @@ var ts; case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 247 /* EnumMember */: - case 245 /* PropertyAssignment */: - case 166 /* PropertyAccessExpression */: + case 249 /* EnumMember */: + case 247 /* PropertyAssignment */: + case 168 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; case 135 /* QualifiedName */: @@ -5470,11 +5597,11 @@ var ts; return parent.kind === 154 /* TypeQuery */; } return false; - case 163 /* BindingElement */: - case 226 /* ImportSpecifier */: + case 165 /* BindingElement */: + case 228 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 230 /* ExportSpecifier */: + case 232 /* ExportSpecifier */: // Any name in an export specifier return true; } @@ -5490,12 +5617,12 @@ var ts; // export = ... // export default ... function isAliasSymbolDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ || - node.kind === 223 /* ImportClause */ && !!node.name || - node.kind === 224 /* NamespaceImport */ || - node.kind === 226 /* ImportSpecifier */ || - node.kind === 230 /* ExportSpecifier */ || - node.kind === 227 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; + return node.kind === 223 /* ImportEqualsDeclaration */ || + node.kind === 225 /* ImportClause */ && !!node.name || + node.kind === 226 /* NamespaceImport */ || + node.kind === 228 /* ImportSpecifier */ || + node.kind === 232 /* ExportSpecifier */ || + node.kind === 229 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -5643,7 +5770,7 @@ var ts; return node.kind === 69 /* Identifier */ && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; - function isModifier(token) { + function isModifierKind(token) { switch (token) { case 115 /* AbstractKeyword */: case 118 /* AsyncKeyword */: @@ -5659,39 +5786,73 @@ var ts; } return false; } - ts.isModifier = isModifier; + ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); return root.kind === 138 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 163 /* BindingElement */) { + while (node.kind === 165 /* BindingElement */) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 218 /* ModuleDeclaration */ || n.kind === 248 /* SourceFile */; + return isFunctionLike(n) || n.kind === 220 /* ModuleDeclaration */ || n.kind === 250 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function cloneEntityName(node) { - if (node.kind === 69 /* Identifier */) { - var clone_1 = createSynthesizedNode(69 /* Identifier */); - clone_1.text = node.text; - return clone_1; + /** + * Creates a shallow, memberwise clone of a node. The "kind", "pos", "end", "flags", and "parent" + * properties are excluded by default, and can be provided via the "location", "flags", and + * "parent" parameters. + * @param node The node to clone. + * @param location An optional TextRange to use to supply the new position. + * @param flags The NodeFlags to use for the cloned node. + * @param parent The parent for the new node. + */ + function cloneNode(node, location, flags, parent) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + var clone = location !== undefined + ? ts.createNode(node.kind, location.pos, location.end) + : createSynthesizedNode(node.kind); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; } - else { - var clone_2 = createSynthesizedNode(135 /* QualifiedName */); - clone_2.left = cloneEntityName(node.left); - clone_2.left.parent = clone_2; - clone_2.right = cloneEntityName(node.right); - clone_2.right.parent = clone_2; - return clone_2; + if (flags !== undefined) { + clone.flags = flags; } + if (parent !== undefined) { + clone.parent = parent; + } + return clone; + } + ts.cloneNode = cloneNode; + /** + * Creates a deep clone of an EntityName, with new parent pointers. + * @param node The EntityName to clone. + * @param parent The parent for the cloned node. + */ + function cloneEntityName(node, parent) { + var clone = cloneNode(node, node, node.flags, parent); + if (isQualifiedName(clone)) { + var left = clone.left, right = clone.right; + clone.left = cloneEntityName(left, clone); + clone.right = cloneNode(right, right, right.flags, parent); + } + return clone; } ts.cloneEntityName = cloneEntityName; + function isQualifiedName(node) { + return node.kind === 135 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { return node.pos === -1; } @@ -5906,8 +6067,8 @@ var ts; writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, - increaseIndent: function () { return indent++; }, - decreaseIndent: function () { return indent--; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, getIndent: function () { return indent; }, getTextPos: function () { return output.length; }, getLine: function () { return lineCount + 1; }, @@ -5921,8 +6082,10 @@ var ts; * Resolves a local path to a path which is absolute to the base of the emit */ function getExternalModuleNameFromPath(host, fileName) { - var dir = host.getCurrentDirectory(); - var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, fileName, dir, function (f) { return host.getCanonicalFileName(f); }, /*isAbsolutePathAnUrl*/ false); + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); return ts.removeFileExtension(relativePath); } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; @@ -5938,6 +6101,63 @@ var ts; return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return compilerOptions.module ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { + var options = host.getCompilerOptions(); + // Emit on each source file + if (options.outFile || options.out) { + onBundledEmit(host); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + if (!isDeclarationFile(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, sourceFile.languageVariant === 1 /* JSX */ && options.jsx === 1 /* Preserve */ ? ".jsx" : ".js"); + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitFilePath(jsFilePath, options) : undefined + }; + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); + } + function onBundledEmit(host) { + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + (!isExternalModule(sourceFile) || + (getEmitModuleKind(options) && isExternalModule(sourceFile))); }); // module that can emit - note falsy value from getEmitModuleKind means the module kind that shouldn't be emitted + if (bundledSources.length) { + var jsFilePath = options.outFile || options.out; + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: getDeclarationEmitFilePath(jsFilePath, options) + }; + action(emitFileNames, bundledSources, /*isBundledEmit*/ true); + } + } + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getDeclarationEmitFilePath(jsFilePath, options) { + return options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + } + } + ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); @@ -5946,7 +6166,7 @@ var ts; ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { - diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); }); } ts.writeFile = writeFile; @@ -5970,18 +6190,6 @@ var ts; return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; - function shouldEmitToOwnFile(sourceFile, compilerOptions) { - if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !(compilerOptions.outFile || compilerOptions.out))) { - // 1. in-browser single file compilation scenario - // 2. non .js file - return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); - } - return false; - } - return false; - } - ts.shouldEmitToOwnFile = shouldEmitToOwnFile; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -6225,24 +6433,24 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 169 /* NewExpression */: - case 168 /* CallExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 170 /* TaggedTemplateExpression */: - case 164 /* ArrayLiteralExpression */: - case 172 /* ParenthesizedExpression */: - case 165 /* ObjectLiteralExpression */: - case 186 /* ClassExpression */: - case 173 /* FunctionExpression */: + case 168 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: + case 171 /* NewExpression */: + case 170 /* CallExpression */: + case 235 /* JsxElement */: + case 236 /* JsxSelfClosingElement */: + case 172 /* TaggedTemplateExpression */: + case 166 /* ArrayLiteralExpression */: + case 174 /* ParenthesizedExpression */: + case 167 /* ObjectLiteralExpression */: + case 188 /* ClassExpression */: + case 175 /* FunctionExpression */: case 69 /* Identifier */: case 10 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 11 /* NoSubstitutionTemplateLiteral */: - case 183 /* TemplateExpression */: + case 185 /* TemplateExpression */: case 84 /* FalseKeyword */: case 93 /* NullKeyword */: case 97 /* ThisKeyword */: @@ -6259,7 +6467,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 188 /* ExpressionWithTypeArguments */ && + return node.kind === 190 /* ExpressionWithTypeArguments */ && node.parent.token === 83 /* ExtendsKeyword */ && isClassLike(node.parent.parent); } @@ -6283,15 +6491,15 @@ var ts; } function isRightSideOfQualifiedNameOrPropertyAccess(node) { return (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node); + (node.parent.kind === 168 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 165 /* ObjectLiteralExpression */) { + if (kind === 167 /* ObjectLiteralExpression */) { return expression.properties.length === 0; } - if (kind === 164 /* ArrayLiteralExpression */) { + if (kind === 166 /* ArrayLiteralExpression */) { return expression.elements.length === 0; } return false; @@ -6302,13 +6510,9 @@ var ts; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function hasJavaScriptFileExtension(fileName) { - return ts.fileExtensionIs(fileName, ".js") || ts.fileExtensionIs(fileName, ".jsx"); + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function allowsJsxExpressions(fileName) { - return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx"); - } - ts.allowsJsxExpressions = allowsJsxExpressions; /** * 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. @@ -6343,6 +6547,47 @@ var ts; } return output; } + /** + * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph + * as the fallback implementation does not check for circular references by default. + */ + ts.stringify = typeof JSON !== "undefined" && JSON.stringify + ? JSON.stringify + : stringifyFallback; + /** + * Serialize an object graph into a JSON string. + */ + function stringifyFallback(value) { + // JSON.stringify returns `undefined` here, instead of the string "undefined". + return value === undefined ? undefined : stringifyValue(value); + } + function stringifyValue(value) { + return typeof value === "string" ? "\"" + escapeString(value) + "\"" + : typeof value === "number" ? isFinite(value) ? String(value) : "null" + : typeof value === "boolean" ? value ? "true" : "false" + : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) + : "null"; + } + function cycleCheck(cb, value) { + ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); + value.__cycle = true; + var result = cb(value); + delete value.__cycle; + return result; + } + function stringifyArray(value) { + return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; + } + function stringifyElement(memo, value) { + return (memo ? memo + "," : memo) + stringifyValue(value); + } + function stringifyObject(value) { + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + } + function stringifyProperty(memo, value, key) { + return value === undefined || typeof value === "function" || key === "__cycle" ? memo + : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); + } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; /** * Converts a string to a base-64 encoded ASCII string. @@ -6611,13 +6856,17 @@ var ts; function getTypeParameterOwner(d) { if (d && d.kind === 137 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 215 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 217 /* InterfaceDeclaration */) { return current; } } } } ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return node.flags & 56 /* AccessibilityModifier */ && node.parent.kind === 144 /* Constructor */ && ts.isClassLike(node.parent.parent); + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; })(ts || (ts = {})); /// /// @@ -6627,7 +6876,7 @@ var ts; var NodeConstructor; var SourceFileConstructor; function createNode(kind, pos, end) { - if (kind === 248 /* SourceFile */) { + if (kind === 250 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else { @@ -6677,7 +6926,7 @@ var ts; return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 246 /* ShorthandPropertyAssignment */: + case 248 /* ShorthandPropertyAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -6687,9 +6936,9 @@ var ts; case 138 /* Parameter */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 247 /* PropertyAssignment */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -6713,9 +6962,9 @@ var ts; case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 176 /* ArrowFunction */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -6745,271 +6994,271 @@ var ts; return visitNodes(cbNodes, node.types); case 160 /* ParenthesizedType */: return visitNode(cbNode, node.type); - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: + case 163 /* ObjectBindingPattern */: + case 164 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return visitNodes(cbNodes, node.elements); - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return visitNodes(cbNodes, node.properties); - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 167 /* ElementAccessExpression */: + case 169 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 170 /* TaggedTemplateExpression */: + case 172 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 171 /* TypeAssertionExpression */: + case 173 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 175 /* DeleteExpression */: + case 177 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 176 /* TypeOfExpression */: + case 178 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 177 /* VoidExpression */: + case 179 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 184 /* YieldExpression */: + case 186 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 178 /* AwaitExpression */: + case 180 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 180 /* PostfixUnaryExpression */: + case 182 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 189 /* AsExpression */: + case 191 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 185 /* SpreadElementExpression */: + case 187 /* SpreadElementExpression */: return visitNode(cbNode, node.expression); - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 194 /* Block */: + case 221 /* ModuleBlock */: return visitNodes(cbNodes, node.statements); - case 248 /* SourceFile */: + case 250 /* SourceFile */: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 212 /* VariableDeclarationList */: + case 214 /* VariableDeclarationList */: return visitNodes(cbNodes, node.declarations); - case 195 /* ExpressionStatement */: + case 197 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 196 /* IfStatement */: + case 198 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 197 /* DoStatement */: + case 199 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 198 /* WhileStatement */: + case 200 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 199 /* ForStatement */: + case 201 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 200 /* ForInStatement */: + case 202 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 201 /* ForOfStatement */: + case 203 /* ForOfStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 204 /* ContinueStatement */: + case 205 /* BreakStatement */: return visitNode(cbNode, node.label); - case 204 /* ReturnStatement */: + case 206 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 205 /* WithStatement */: + case 207 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 220 /* CaseBlock */: + case 222 /* CaseBlock */: return visitNodes(cbNodes, node.clauses); - case 241 /* CaseClause */: + case 243 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 242 /* DefaultClause */: + case 244 /* DefaultClause */: return visitNodes(cbNodes, node.statements); - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 208 /* ThrowStatement */: + case 210 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 209 /* TryStatement */: + case 211 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); case 139 /* Decorator */: return visitNode(cbNode, node.expression); - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.heritageClauses) || visitNodes(cbNodes, node.members); - case 216 /* TypeAliasDeclaration */: + case 218 /* TypeAliasDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.members); - case 247 /* EnumMember */: + case 249 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 223 /* ImportClause */: + case 225 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 224 /* NamespaceImport */: + case 226 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 225 /* NamedImports */: - case 229 /* NamedExports */: + case 227 /* NamedImports */: + case 231 /* NamedExports */: return visitNodes(cbNodes, node.elements); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 228 /* ImportSpecifier */: + case 232 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 183 /* TemplateExpression */: + case 185 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 190 /* TemplateSpan */: + case 192 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); case 136 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 243 /* HeritageClause */: + case 245 /* HeritageClause */: return visitNodes(cbNodes, node.types); - case 188 /* ExpressionWithTypeArguments */: + case 190 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 232 /* ExternalModuleReference */: + case 234 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 231 /* MissingDeclaration */: + case 233 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); - case 233 /* JsxElement */: + case 235 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 234 /* JsxSelfClosingElement */: - case 235 /* JsxOpeningElement */: + case 236 /* JsxSelfClosingElement */: + case 237 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 238 /* JsxAttribute */: + case 240 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 239 /* JsxSpreadAttribute */: + case 241 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 240 /* JsxExpression */: + case 242 /* JsxExpression */: return visitNode(cbNode, node.expression); - case 237 /* JsxClosingElement */: + case 239 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 249 /* JSDocTypeExpression */: + case 251 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 253 /* JSDocUnionType */: + case 255 /* JSDocUnionType */: return visitNodes(cbNodes, node.types); - case 254 /* JSDocTupleType */: + case 256 /* JSDocTupleType */: return visitNodes(cbNodes, node.types); - case 252 /* JSDocArrayType */: + case 254 /* JSDocArrayType */: return visitNode(cbNode, node.elementType); - case 256 /* JSDocNonNullableType */: + case 258 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 255 /* JSDocNullableType */: + case 257 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 257 /* JSDocRecordType */: + case 259 /* JSDocRecordType */: return visitNodes(cbNodes, node.members); - case 259 /* JSDocTypeReference */: + case 261 /* JSDocTypeReference */: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); - case 260 /* JSDocOptionalType */: + case 262 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 261 /* JSDocFunctionType */: + case 263 /* JSDocFunctionType */: return visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 262 /* JSDocVariadicType */: + case 264 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 263 /* JSDocConstructorType */: + case 265 /* JSDocConstructorType */: return visitNode(cbNode, node.type); - case 264 /* JSDocThisType */: + case 266 /* JSDocThisType */: return visitNode(cbNode, node.type); - case 258 /* JSDocRecordMember */: + case 260 /* JSDocRecordMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 265 /* JSDocComment */: + case 267 /* JSDocComment */: return visitNodes(cbNodes, node.tags); - case 267 /* JSDocParameterTag */: + case 269 /* JSDocParameterTag */: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 268 /* JSDocReturnTag */: + case 270 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 269 /* JSDocTypeTag */: + case 271 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 270 /* JSDocTemplateTag */: + case 272 /* JSDocTemplateTag */: return visitNodes(cbNodes, node.typeParameters); } } @@ -7150,6 +7399,10 @@ var ts; return result; } Parser.parseSourceFile = parseSourceFile; + function getLanguageVariant(fileName) { + // .tsx and .jsx files are treated as jsx language variant. + return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx") ? 1 /* JSX */ : 0 /* Standard */; + } function initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor) { NodeConstructor = ts.objectAllocator.getNodeConstructor(); SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); @@ -7166,7 +7419,7 @@ var ts; scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(ts.allowsJsxExpressions(fileName) ? 1 /* JSX */ : 0 /* Standard */); + scanner.setLanguageVariant(getLanguageVariant(fileName)); } function clearState() { // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. @@ -7213,8 +7466,8 @@ var ts; // Add additional cases as necessary depending on how we see JSDoc comments used // in the wild. switch (node.kind) { - case 193 /* VariableStatement */: - case 213 /* FunctionDeclaration */: + case 195 /* VariableStatement */: + case 215 /* FunctionDeclaration */: case 138 /* Parameter */: addJSDocComment(node); } @@ -7258,14 +7511,14 @@ var ts; function createSourceFile(fileName, languageVersion) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(248 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(250 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 /* DeclarationFile */ : 0; - sourceFile.languageVariant = ts.allowsJsxExpressions(sourceFile.fileName) ? 1 /* JSX */ : 0 /* Standard */; + sourceFile.languageVariant = getLanguageVariant(sourceFile.fileName); return sourceFile; } function setContextFlag(val, flag) { @@ -7298,10 +7551,10 @@ var ts; var contextFlagsToClear = context & contextFlags; if (contextFlagsToClear) { // clear the requested context flags - setContextFlag(false, contextFlagsToClear); + setContextFlag(/*val*/ false, contextFlagsToClear); var result = func(); // restore the context flags we just cleared - setContextFlag(true, contextFlagsToClear); + setContextFlag(/*val*/ true, contextFlagsToClear); return result; } // no need to do anything special as we are not in any of the requested contexts @@ -7317,10 +7570,10 @@ var ts; var contextFlagsToSet = context & ~contextFlags; if (contextFlagsToSet) { // set the requested context flags - setContextFlag(true, contextFlagsToSet); + setContextFlag(/*val*/ true, contextFlagsToSet); var result = func(); // reset the context flags we just set - setContextFlag(false, contextFlagsToSet); + setContextFlag(/*val*/ false, contextFlagsToSet); return result; } // no need to do anything special as we are already in all of the requested contexts @@ -7335,9 +7588,6 @@ var ts; function doInYieldContext(func) { return doInsideOfContext(2 /* Yield */, func); } - function doOutsideOfYieldContext(func) { - return doOutsideOfContext(2 /* Yield */, func); - } function doInDecoratorContext(func) { return doInsideOfContext(4 /* Decorator */, func); } @@ -7350,9 +7600,6 @@ var ts; function doInYieldAndAwaitContext(func) { return doInsideOfContext(2 /* Yield */ | 8 /* Await */, func); } - function doOutsideOfYieldAndAwaitContext(func) { - return doOutsideOfContext(2 /* Yield */ | 8 /* Await */, func); - } function inContext(flags) { return (contextFlags & flags) !== 0; } @@ -7396,9 +7643,6 @@ var ts; function nextToken() { return token = scanner.scan(); } - function getTokenPos(pos) { - return ts.skipTrivia(sourceText, pos); - } function reScanGreaterToken() { return token = scanner.reScanGreaterToken(); } @@ -7605,10 +7849,10 @@ var ts; return parseIdentifierName(); } function parsePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ true); + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); } function parseSimplePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ false); + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false); } function isSimplePropertyName() { return token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token); @@ -7629,6 +7873,13 @@ var ts; function parseContextualModifier(t) { return token === t && tryParse(nextTokenCanFollowModifier); } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } function nextTokenCanFollowModifier() { if (token === 74 /* ConstKeyword */) { // 'const' is only a modifier if followed by 'enum'. @@ -7648,14 +7899,10 @@ var ts; nextToken(); return canFollowModifier(); } - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); + return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifier(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { return token === 19 /* OpenBracketToken */ @@ -7861,7 +8108,7 @@ var ts; function isInSomeParsingContext() { for (var kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & (1 << kind)) { - if (isListElement(kind, /* inErrorRecovery */ true) || isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; } } @@ -7875,7 +8122,7 @@ var ts; var result = []; result.pos = getNodePos(); while (!isListTerminator(kind)) { - if (isListElement(kind, /* inErrorRecovery */ false)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); result.push(element); continue; @@ -8020,7 +8267,7 @@ var ts; case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 141 /* PropertyDeclaration */: - case 191 /* SemicolonClassElement */: + case 193 /* SemicolonClassElement */: return true; case 143 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal @@ -8037,8 +8284,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: return true; } } @@ -8047,42 +8294,42 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: - case 193 /* VariableStatement */: - case 192 /* Block */: - case 196 /* IfStatement */: - case 195 /* ExpressionStatement */: - case 208 /* ThrowStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 194 /* EmptyStatement */: - case 209 /* TryStatement */: - case 207 /* LabeledStatement */: - case 197 /* DoStatement */: - case 210 /* DebuggerStatement */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: - case 227 /* ExportAssignment */: - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 216 /* TypeAliasDeclaration */: + case 215 /* FunctionDeclaration */: + case 195 /* VariableStatement */: + case 194 /* Block */: + case 198 /* IfStatement */: + case 197 /* ExpressionStatement */: + case 210 /* ThrowStatement */: + case 206 /* ReturnStatement */: + case 208 /* SwitchStatement */: + case 205 /* BreakStatement */: + case 204 /* ContinueStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 201 /* ForStatement */: + case 200 /* WhileStatement */: + case 207 /* WithStatement */: + case 196 /* EmptyStatement */: + case 211 /* TryStatement */: + case 209 /* LabeledStatement */: + case 199 /* DoStatement */: + case 212 /* DebuggerStatement */: + case 224 /* ImportDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 230 /* ExportDeclaration */: + case 229 /* ExportAssignment */: + case 220 /* ModuleDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: + case 218 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 247 /* EnumMember */; + return node.kind === 249 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { @@ -8098,7 +8345,7 @@ var ts; return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 211 /* VariableDeclaration */) { + if (node.kind !== 213 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -8174,7 +8421,7 @@ var ts; result.pos = getNodePos(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { - if (isListElement(kind, /* inErrorRecovery */ false)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(24 /* CommaToken */)) { @@ -8269,14 +8516,14 @@ var ts; // Report that we need an identifier. However, report it right after the dot, // and not on the next token. This is because the next token might actually // be an identifier and the error would be quite confusing. - return createMissingNode(69 /* Identifier */, /*reportAtCurrentToken*/ true, ts.Diagnostics.Identifier_expected); + return createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(183 /* TemplateExpression */); - template.head = parseLiteralNode(); + var template = createNode(185 /* TemplateExpression */); + template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = []; templateSpans.pos = getNodePos(); @@ -8288,12 +8535,12 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(190 /* TemplateSpan */); + var span = createNode(192 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token === 16 /* CloseBraceToken */) { reScanTemplateToken(); - literal = parseLiteralNode(); + literal = parseTemplateLiteralFragment(); } else { literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); @@ -8301,8 +8548,17 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(162 /* StringLiteralType */, /*internName*/ true); + } function parseLiteralNode(internName) { - var node = createNode(token); + return parseLiteralLikeNode(token, internName); + } + function parseTemplateLiteralFragment() { + return parseLiteralLikeNode(token, /*internName*/ false); + } + function parseLiteralLikeNode(kind, internName) { + var node = createNode(kind); var text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -8331,11 +8587,7 @@ var ts; function parseTypeReferenceOrTypePredicate() { var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); if (typeName.kind === 69 /* Identifier */ && token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var node_1 = createNode(150 /* TypePredicate */, typeName.pos); - node_1.parameterName = typeName; - node_1.type = parseType(); - return finishNode(node_1); + return parseTypePredicate(typeName); } var node = createNode(151 /* TypeReference */, typeName.pos); node.typeName = typeName; @@ -8344,6 +8596,18 @@ var ts; } return finishNode(node); } + function parseTypePredicate(lhs) { + nextToken(); + var node = createNode(150 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(161 /* ThisType */); + nextToken(); + return finishNode(node); + } function parseTypeQuery() { var node = createNode(154 /* TypeQuery */); parseExpected(101 /* TypeOfKeyword */); @@ -8386,7 +8650,7 @@ var ts; return undefined; } function isStartOfParameter() { - return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifier(token) || token === 55 /* AtToken */; + return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 /* AtToken */; } function setModifiers(node, modifiers) { if (modifiers) { @@ -8402,7 +8666,7 @@ var ts; // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifier(token)) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { // in cases like // 'use strict' // function foo(static) @@ -8523,7 +8787,7 @@ var ts; if (token === 22 /* DotDotDotToken */ || token === 20 /* CloseBracketToken */) { return true; } - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -8580,6 +8844,12 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); + if (token === 56 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + property.initializer = parseNonParameterInitializer(); + } parseTypeMemberSemicolon(); return finishNode(property); } @@ -8591,7 +8861,7 @@ var ts; case 19 /* OpenBracketToken */: return true; default: - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { var result = lookAhead(isStartOfIndexSignatureDeclaration); if (result) { return result; @@ -8601,7 +8871,7 @@ var ts; } } function isStartOfIndexSignatureDeclaration() { - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { nextToken(); } return isIndexSignature(); @@ -8639,7 +8909,7 @@ var ts; // when incrementally parsing as the parser will produce the Index declaration // if it has the same text regardless of whether it is inside a class or an // object type. - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { var result = tryParse(parseIndexSignatureWithModifiers); if (result) { return result; @@ -8713,10 +8983,18 @@ var ts; var node = tryParse(parseKeywordAndNoDot); return node || parseTypeReferenceOrTypePredicate(); case 9 /* StringLiteral */: - return parseLiteralNode(/*internName*/ true); + return parseStringLiteralTypeNode(); case 103 /* VoidKeyword */: - case 97 /* ThisKeyword */: return parseTokenNode(); + case 97 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } case 101 /* TypeOfKeyword */: return parseTypeQuery(); case 15 /* OpenBraceToken */: @@ -8801,11 +9079,11 @@ var ts; // ( ... return true; } - if (isIdentifier() || ts.isModifier(token)) { + if (isIdentifier() || ts.isModifierKind(token)) { nextToken(); if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */ || - isIdentifier() || ts.isModifier(token)) { + isIdentifier() || ts.isModifierKind(token)) { // ( id : // ( id , // ( id ? @@ -8906,9 +9184,6 @@ var ts; token !== 55 /* AtToken */ && isStartOfExpression(); } - function allowInAndParseExpression() { - return allowInAnd(parseExpression); - } function parseExpression() { // Expression[in]: // AssignmentExpression[in] @@ -8916,7 +9191,7 @@ var ts; // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; @@ -8924,7 +9199,7 @@ var ts; expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } return expr; } @@ -9029,7 +9304,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(184 /* YieldExpression */); + var node = createNode(186 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -9049,14 +9324,14 @@ var ts; } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(174 /* ArrowFunction */, identifier.pos); + var node = createNode(176 /* ArrowFunction */, identifier.pos); var parameter = createNode(138 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = [parameter]; node.parameters.pos = parameter.pos; node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, false, ts.Diagnostics._0_expected, "=>"); + node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ false); return finishNode(node); } @@ -9160,7 +9435,7 @@ var ts; return 1 /* True */; } // This *could* be a parenthesized arrow function. - // Return Unknown to const the caller know. + // Return Unknown to let the caller know. return 2 /* Unknown */; } else { @@ -9202,7 +9477,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(174 /* ArrowFunction */); + var node = createNode(176 /* ArrowFunction */); setModifiers(node, parseModifiersForArrowFunction()); var isAsync = !!(node.flags & 256 /* Async */); // Arrow functions are never generators. @@ -9246,7 +9521,7 @@ var ts; // user meant to supply a block. For example, if the user wrote: // // a => - // const v = 0; + // let v = 0; // } // // they may be missing an open brace. Check to see if that's the case so we can @@ -9268,7 +9543,7 @@ var ts; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(182 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(184 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -9389,39 +9664,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(181 /* BinaryExpression */, left.pos); + var node = createNode(183 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(189 /* AsExpression */, left.pos); + var node = createNode(191 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(179 /* PrefixUnaryExpression */); + var node = createNode(181 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(175 /* DeleteExpression */); + var node = createNode(177 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(176 /* TypeOfExpression */); + var node = createNode(178 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(177 /* VoidExpression */); + var node = createNode(179 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -9437,7 +9712,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(178 /* AwaitExpression */); + var node = createNode(180 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -9463,7 +9738,7 @@ var ts; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === 38 /* AsteriskAsteriskToken */) { var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 171 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 173 /* 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); } else { @@ -9553,7 +9828,7 @@ var ts; */ function parseIncrementExpression() { if (token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) { - var node = createNode(179 /* PrefixUnaryExpression */); + var node = createNode(181 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -9566,7 +9841,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(180 /* PostfixUnaryExpression */, expression.pos); + var node = createNode(182 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -9670,24 +9945,37 @@ var ts; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(166 /* PropertyAccessExpression */, expression.pos); + var node = createNode(168 /* PropertyAccessExpression */, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 69 /* Identifier */) { + return lhs.text === rhs.text; + } + return lhs.right.text === rhs.right.text && + tagNamesAreEquivalent(lhs.left, rhs.left); + } function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 235 /* JsxOpeningElement */) { - var node = createNode(233 /* JsxElement */, opening.pos); + if (opening.kind === 237 /* JsxOpeningElement */) { + var node = createNode(235 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 236 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -9702,7 +9990,7 @@ var ts; var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(181 /* BinaryExpression */, result.pos); + var badNode = createNode(183 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -9714,13 +10002,13 @@ var ts; return result; } function parseJsxText() { - var node = createNode(236 /* JsxText */, scanner.getStartPos()); + var node = createNode(238 /* JsxText */, scanner.getStartPos()); token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token) { - case 236 /* JsxText */: + case 238 /* JsxText */: return parseJsxText(); case 15 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); @@ -9737,10 +10025,13 @@ var ts; while (true) { token = scanner.reScanJsxToken(); if (token === 26 /* LessThanSlashToken */) { + // Closing tag break; } else if (token === 1 /* EndOfFileToken */) { - parseErrorAtCurrentToken(ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + // 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)); break; } result.push(parseJsxChild()); @@ -9759,7 +10050,7 @@ var ts; // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(235 /* JsxOpeningElement */, fullStart); + node = createNode(237 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { @@ -9768,10 +10059,10 @@ var ts; parseExpected(27 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(234 /* JsxSelfClosingElement */, fullStart); + node = createNode(236 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -9790,16 +10081,16 @@ var ts; return elementName; } function parseJsxExpression(inExpressionContext) { - var node = createNode(240 /* JsxExpression */); + var node = createNode(242 /* JsxExpression */); parseExpected(15 /* OpenBraceToken */); if (token !== 16 /* CloseBraceToken */) { - node.expression = parseExpression(); + node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { parseExpected(16 /* CloseBraceToken */); } else { - parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*advance*/ false); + parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); @@ -9809,7 +10100,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(238 /* JsxAttribute */); + var node = createNode(240 /* JsxAttribute */); node.name = parseIdentifierName(); if (parseOptional(56 /* EqualsToken */)) { switch (token) { @@ -9824,7 +10115,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(239 /* JsxSpreadAttribute */); + var node = createNode(241 /* JsxSpreadAttribute */); parseExpected(15 /* OpenBraceToken */); parseExpected(22 /* DotDotDotToken */); node.expression = parseExpression(); @@ -9832,20 +10123,20 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(237 /* JsxClosingElement */); + var node = createNode(239 /* JsxClosingElement */); parseExpected(26 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { parseExpected(27 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(171 /* TypeAssertionExpression */); + var node = createNode(173 /* TypeAssertionExpression */); parseExpected(25 /* LessThanToken */); node.type = parseType(); parseExpected(27 /* GreaterThanToken */); @@ -9856,7 +10147,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(21 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(166 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(168 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -9865,7 +10156,7 @@ var ts; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(19 /* OpenBracketToken */)) { - var indexedAccess = createNode(167 /* ElementAccessExpression */, expression.pos); + var indexedAccess = createNode(169 /* ElementAccessExpression */, expression.pos); 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. @@ -9881,7 +10172,7 @@ var ts; continue; } if (token === 11 /* NoSubstitutionTemplateLiteral */ || token === 12 /* TemplateHead */) { - var tagExpression = createNode(170 /* TaggedTemplateExpression */, expression.pos); + var tagExpression = createNode(172 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 11 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() @@ -9904,7 +10195,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(168 /* CallExpression */, expression.pos); + var callExpr = createNode(170 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -9912,7 +10203,7 @@ var ts; continue; } else if (token === 17 /* OpenParenToken */) { - var callExpr = createNode(168 /* CallExpression */, expression.pos); + var callExpr = createNode(170 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -10022,28 +10313,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(172 /* ParenthesizedExpression */); + var node = createNode(174 /* ParenthesizedExpression */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(185 /* SpreadElementExpression */); + var node = createNode(187 /* SpreadElementExpression */); parseExpected(22 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 22 /* DotDotDotToken */ ? parseSpreadElement() : - token === 24 /* CommaToken */ ? createNode(187 /* OmittedExpression */) : + token === 24 /* CommaToken */ ? createNode(189 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(164 /* ArrayLiteralExpression */); + var node = createNode(166 /* ArrayLiteralExpression */); parseExpected(19 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) node.flags |= 1024 /* MultiLine */; @@ -10070,7 +10361,6 @@ var ts; } var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); - var nameToken = token; var propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); @@ -10084,7 +10374,7 @@ var ts; // 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 */); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(246 /* ShorthandPropertyAssignment */, fullStart); + var shorthandDeclaration = createNode(248 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; var equalsToken = parseOptionalToken(56 /* EqualsToken */); @@ -10095,7 +10385,8 @@ var ts; return finishNode(shorthandDeclaration); } else { - var propertyAssignment = createNode(245 /* PropertyAssignment */, fullStart); + var propertyAssignment = createNode(247 /* PropertyAssignment */, fullStart); + propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(54 /* ColonToken */); @@ -10104,7 +10395,7 @@ var ts; } } function parseObjectLiteralExpression() { - var node = createNode(165 /* ObjectLiteralExpression */); + var node = createNode(167 /* ObjectLiteralExpression */); parseExpected(15 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.flags |= 1024 /* MultiLine */; @@ -10121,9 +10412,9 @@ var ts; // function BindingIdentifier[opt](FormalParameters){ FunctionBody } var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } - var node = createNode(173 /* FunctionExpression */); + var node = createNode(175 /* FunctionExpression */); setModifiers(node, parseModifiers()); parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); @@ -10137,7 +10428,7 @@ var ts; fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } return finishNode(node); } @@ -10145,7 +10436,7 @@ var ts; return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(169 /* NewExpression */); + var node = createNode(171 /* NewExpression */); parseExpected(92 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -10156,7 +10447,7 @@ var ts; } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(192 /* Block */); + var node = createNode(194 /* Block */); if (parseExpected(15 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); @@ -10175,23 +10466,23 @@ var ts; // arrow function. The body of the function is not in [Decorator] context. var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return block; } function parseEmptyStatement() { - var node = createNode(194 /* EmptyStatement */); + var node = createNode(196 /* EmptyStatement */); parseExpected(23 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(196 /* IfStatement */); + var node = createNode(198 /* IfStatement */); parseExpected(88 /* IfKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -10201,7 +10492,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(197 /* DoStatement */); + var node = createNode(199 /* DoStatement */); parseExpected(79 /* DoKeyword */); node.statement = parseStatement(); parseExpected(104 /* WhileKeyword */); @@ -10216,7 +10507,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(198 /* WhileStatement */); + var node = createNode(200 /* WhileStatement */); parseExpected(104 /* WhileKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -10239,21 +10530,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(90 /* InKeyword */)) { - var forInStatement = createNode(200 /* ForInStatement */, pos); + var forInStatement = createNode(202 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else if (parseOptional(134 /* OfKeyword */)) { - var forOfStatement = createNode(201 /* ForOfStatement */, pos); + var forOfStatement = createNode(203 /* ForOfStatement */, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(18 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(199 /* ForStatement */, pos); + var forStatement = createNode(201 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(23 /* SemicolonToken */); if (token !== 23 /* SemicolonToken */ && token !== 18 /* CloseParenToken */) { @@ -10271,7 +10562,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); + parseExpected(kind === 205 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -10279,7 +10570,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(204 /* ReturnStatement */); + var node = createNode(206 /* ReturnStatement */); parseExpected(94 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -10288,7 +10579,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(205 /* WithStatement */); + var node = createNode(207 /* WithStatement */); parseExpected(105 /* WithKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -10297,7 +10588,7 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(241 /* CaseClause */); + var node = createNode(243 /* CaseClause */); parseExpected(71 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(54 /* ColonToken */); @@ -10305,7 +10596,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(242 /* DefaultClause */); + var node = createNode(244 /* DefaultClause */); parseExpected(77 /* DefaultKeyword */); parseExpected(54 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); @@ -10315,12 +10606,12 @@ var ts; return token === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(206 /* SwitchStatement */); + var node = createNode(208 /* SwitchStatement */); parseExpected(96 /* SwitchKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); - var caseBlock = createNode(220 /* CaseBlock */, scanner.getStartPos()); + var caseBlock = createNode(222 /* CaseBlock */, scanner.getStartPos()); parseExpected(15 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(16 /* CloseBraceToken */); @@ -10335,7 +10626,7 @@ var ts; // directly as that might consume an expression on the following line. // We just return 'undefined' in that case. The actual error will be reported in the // grammar walker. - var node = createNode(208 /* ThrowStatement */); + var node = createNode(210 /* ThrowStatement */); parseExpected(98 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -10343,7 +10634,7 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(209 /* TryStatement */); + var node = createNode(211 /* TryStatement */); parseExpected(100 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); node.catchClause = token === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -10356,7 +10647,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(244 /* CatchClause */); + var result = createNode(246 /* CatchClause */); parseExpected(72 /* CatchKeyword */); if (parseExpected(17 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); @@ -10366,7 +10657,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(210 /* DebuggerStatement */); + var node = createNode(212 /* DebuggerStatement */); parseExpected(76 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -10378,13 +10669,13 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 69 /* Identifier */ && parseOptional(54 /* ColonToken */)) { - var labeledStatement = createNode(207 /* LabeledStatement */, fullStart); + var labeledStatement = createNode(209 /* LabeledStatement */, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - var expressionStatement = createNode(195 /* ExpressionStatement */, fullStart); + var expressionStatement = createNode(197 /* ExpressionStatement */, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); @@ -10558,9 +10849,9 @@ var ts; case 86 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 75 /* ContinueKeyword */: - return parseBreakOrContinueStatement(202 /* ContinueStatement */); + return parseBreakOrContinueStatement(204 /* ContinueStatement */); case 70 /* BreakKeyword */: - return parseBreakOrContinueStatement(203 /* BreakStatement */); + return parseBreakOrContinueStatement(205 /* BreakStatement */); case 94 /* ReturnKeyword */: return parseReturnStatement(); case 105 /* WithKeyword */: @@ -10633,7 +10924,7 @@ var ts; if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var node = createMissingNode(231 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(233 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; setModifiers(node, modifiers); @@ -10655,16 +10946,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token === 24 /* CommaToken */) { - return createNode(187 /* OmittedExpression */); + return createNode(189 /* OmittedExpression */); } - var node = createNode(163 /* BindingElement */); + var node = createNode(165 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(/*inParameter*/ false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(163 /* BindingElement */); + var node = createNode(165 /* BindingElement */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== 54 /* ColonToken */) { @@ -10679,14 +10970,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(161 /* ObjectBindingPattern */); + var node = createNode(163 /* ObjectBindingPattern */); parseExpected(15 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(16 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(162 /* ArrayBindingPattern */); + var node = createNode(164 /* ArrayBindingPattern */); parseExpected(19 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(20 /* CloseBracketToken */); @@ -10705,7 +10996,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(211 /* VariableDeclaration */); + var node = createNode(213 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -10714,7 +11005,7 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(212 /* VariableDeclarationList */); + var node = createNode(214 /* VariableDeclarationList */); switch (token) { case 102 /* VarKeyword */: break; @@ -10752,7 +11043,7 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 18 /* CloseParenToken */; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(193 /* VariableStatement */, fullStart); + var node = createNode(195 /* VariableStatement */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); @@ -10760,7 +11051,7 @@ var ts; return finishNode(node); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(213 /* FunctionDeclaration */, fullStart); + var node = createNode(215 /* FunctionDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(87 /* FunctionKeyword */); @@ -10858,7 +11149,7 @@ var ts; return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. - while (ts.isModifier(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 @@ -10919,7 +11210,7 @@ var ts; } if (!decorators) { decorators = []; - decorators.pos = scanner.getStartPos(); + decorators.pos = decoratorStart; } var decorator = createNode(139 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); @@ -10930,14 +11221,30 @@ var ts; } return decorators; } - function parseModifiers() { + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token; - if (!parseAnyContextualModifier()) { - break; + 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)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } } if (!modifiers) { modifiers = []; @@ -10970,13 +11277,13 @@ var ts; } function parseClassElement() { if (token === 23 /* SemicolonToken */) { - var result = createNode(191 /* SemicolonClassElement */); + var result = createNode(193 /* SemicolonClassElement */); nextToken(); return finishNode(result); } var fullStart = getNodePos(); var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; @@ -11008,10 +11315,10 @@ var ts; return parseClassDeclarationOrExpression( /*fullStart*/ scanner.getStartPos(), /*decorators*/ undefined, - /*modifiers*/ undefined, 186 /* ClassExpression */); + /*modifiers*/ undefined, 188 /* ClassExpression */); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 214 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 216 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); @@ -11036,8 +11343,8 @@ var ts; // implements is a future reserved word so // 'class implements' might mean either // - class expression with omitted name, 'implements' starts heritage clause - // - class with name 'implements' - // 'isImplementsClause' helps to disambiguate between these two cases + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases return isIdentifier() && !isImplementsClause() ? parseIdentifier() : undefined; @@ -11053,12 +11360,9 @@ var ts; } return undefined; } - function parseHeritageClausesWorker() { - return parseList(20 /* HeritageClauses */, parseHeritageClause); - } function parseHeritageClause() { if (token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */) { - var node = createNode(243 /* HeritageClause */); + var node = createNode(245 /* HeritageClause */); node.token = token; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); @@ -11067,7 +11371,7 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(188 /* ExpressionWithTypeArguments */); + var node = createNode(190 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); @@ -11081,7 +11385,7 @@ var ts; return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(215 /* InterfaceDeclaration */, fullStart); + var node = createNode(217 /* InterfaceDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(107 /* InterfaceKeyword */); @@ -11092,7 +11396,7 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(216 /* TypeAliasDeclaration */, fullStart); + var node = createNode(218 /* TypeAliasDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(132 /* TypeKeyword */); @@ -11108,13 +11412,13 @@ var ts; // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNode(247 /* EnumMember */, scanner.getStartPos()); + var node = createNode(249 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(217 /* EnumDeclaration */, fullStart); + var node = createNode(219 /* EnumDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(81 /* EnumKeyword */); @@ -11129,7 +11433,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(219 /* ModuleBlock */, scanner.getStartPos()); + var node = createNode(221 /* ModuleBlock */, scanner.getStartPos()); if (parseExpected(15 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); @@ -11140,7 +11444,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(218 /* ModuleDeclaration */, fullStart); + var node = createNode(220 /* ModuleDeclaration */, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 65536 /* Namespace */; @@ -11154,7 +11458,7 @@ var ts; return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(218 /* ModuleDeclaration */, fullStart); + var node = createNode(220 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parseLiteralNode(/*internName*/ true); @@ -11184,11 +11488,6 @@ var ts; function nextTokenIsSlash() { return nextToken() === 39 /* SlashToken */; } - function nextTokenIsCommaOrFromKeyword() { - nextToken(); - return token === 24 /* CommaToken */ || - token === 133 /* FromKeyword */; - } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(89 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); @@ -11199,7 +11498,7 @@ var ts; // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - var importEqualsDeclaration = createNode(221 /* ImportEqualsDeclaration */, fullStart); + var importEqualsDeclaration = createNode(223 /* ImportEqualsDeclaration */, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -11210,7 +11509,7 @@ var ts; } } // Import statement - var importDeclaration = createNode(222 /* ImportDeclaration */, fullStart); + var importDeclaration = createNode(224 /* ImportDeclaration */, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); // ImportDeclaration: @@ -11233,7 +11532,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(223 /* ImportClause */, fullStart); + var importClause = createNode(225 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -11243,7 +11542,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(24 /* CommaToken */)) { - importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(225 /* NamedImports */); + importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(227 /* NamedImports */); } return finishNode(importClause); } @@ -11253,7 +11552,7 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(232 /* ExternalModuleReference */); + var node = createNode(234 /* ExternalModuleReference */); parseExpected(127 /* RequireKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = parseModuleSpecifier(); @@ -11261,21 +11560,22 @@ var ts; return finishNode(node); } function parseModuleSpecifier() { - // We allow arbitrary expressions here, even though the grammar only allows string - // literals. We check to ensure that it is only a string literal later in the grammar - // walker. - var result = parseExpression(); - // Ensure the string being required is in our 'identifier' table. This will ensure - // that features like 'find refs' will look inside this file when search for its name. - if (result.kind === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */) { + var result = parseLiteralNode(); internIdentifier(result.text); + return result; + } + else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. + return parseExpression(); } - return result; } function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(224 /* NamespaceImport */); + var namespaceImport = createNode(226 /* NamespaceImport */); parseExpected(37 /* AsteriskToken */); parseExpected(116 /* AsKeyword */); namespaceImport.name = parseIdentifier(); @@ -11290,14 +11590,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(21 /* ImportOrExportSpecifiers */, kind === 225 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); + node.elements = parseBracketedList(21 /* ImportOrExportSpecifiers */, kind === 227 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(230 /* ExportSpecifier */); + return parseImportOrExportSpecifier(232 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(226 /* ImportSpecifier */); + return parseImportOrExportSpecifier(228 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -11322,14 +11622,14 @@ var ts; else { node.name = identifierName; } - if (kind === 226 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 228 /* ImportSpecifier */ && checkIdentifierIsKeyword) { // Report error identifier expected parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228 /* ExportDeclaration */, fullStart); + var node = createNode(230 /* ExportDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(37 /* AsteriskToken */)) { @@ -11337,7 +11637,7 @@ var ts; node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(229 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(231 /* NamedExports */); // 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. @@ -11350,7 +11650,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(227 /* ExportAssignment */, fullStart); + var node = createNode(229 /* ExportAssignment */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(56 /* EqualsToken */)) { @@ -11373,11 +11673,13 @@ var ts; // reference comment. while (true) { var kind = triviaScanner.scan(); - if (kind === 5 /* WhitespaceTrivia */ || kind === 4 /* NewLineTrivia */ || kind === 3 /* MultiLineCommentTrivia */) { - continue; - } if (kind !== 2 /* SingleLineCommentTrivia */) { - break; + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } } var range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; var comment = sourceText.substring(range.pos, range.end); @@ -11423,10 +11725,10 @@ var ts; function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return node.flags & 2 /* Export */ - || node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 232 /* ExternalModuleReference */ - || node.kind === 222 /* ImportDeclaration */ - || node.kind === 227 /* ExportAssignment */ - || node.kind === 228 /* ExportDeclaration */ + || node.kind === 223 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 234 /* ExternalModuleReference */ + || node.kind === 224 /* ImportDeclaration */ + || node.kind === 229 /* ExportAssignment */ + || node.kind === 230 /* ExportDeclaration */ ? node : undefined; }); @@ -11501,7 +11803,7 @@ var ts; scanner.setText(sourceText, start, length); // Prime the first token for us to start processing. token = nextToken(); - var result = createNode(249 /* JSDocTypeExpression */); + var result = createNode(251 /* JSDocTypeExpression */); parseExpected(15 /* OpenBraceToken */); result.type = parseJSDocTopLevelType(); parseExpected(16 /* CloseBraceToken */); @@ -11512,12 +11814,12 @@ var ts; function parseJSDocTopLevelType() { var type = parseJSDocType(); if (token === 47 /* BarToken */) { - var unionType = createNode(253 /* JSDocUnionType */, type.pos); + var unionType = createNode(255 /* JSDocUnionType */, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } if (token === 56 /* EqualsToken */) { - var optionalType = createNode(260 /* JSDocOptionalType */, type.pos); + var optionalType = createNode(262 /* JSDocOptionalType */, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -11528,20 +11830,20 @@ var ts; var type = parseBasicTypeExpression(); while (true) { if (token === 19 /* OpenBracketToken */) { - var arrayType = createNode(252 /* JSDocArrayType */, type.pos); + var arrayType = createNode(254 /* JSDocArrayType */, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20 /* CloseBracketToken */); type = finishNode(arrayType); } else if (token === 53 /* QuestionToken */) { - var nullableType = createNode(255 /* JSDocNullableType */, type.pos); + var nullableType = createNode(257 /* JSDocNullableType */, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } else if (token === 49 /* ExclamationToken */) { - var nonNullableType = createNode(256 /* JSDocNonNullableType */, type.pos); + var nonNullableType = createNode(258 /* JSDocNonNullableType */, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -11586,27 +11888,27 @@ var ts; return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(264 /* JSDocThisType */); + var result = createNode(266 /* JSDocThisType */); nextToken(); parseExpected(54 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(263 /* JSDocConstructorType */); + var result = createNode(265 /* JSDocConstructorType */); nextToken(); parseExpected(54 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(262 /* JSDocVariadicType */); + var result = createNode(264 /* JSDocVariadicType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(261 /* JSDocFunctionType */); + var result = createNode(263 /* JSDocFunctionType */); nextToken(); parseExpected(17 /* OpenParenToken */); result.parameters = parseDelimitedList(22 /* JSDocFunctionParameters */, parseJSDocParameter); @@ -11623,14 +11925,8 @@ var ts; parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocOptionalType(type) { - var result = createNode(260 /* JSDocOptionalType */, type.pos); - nextToken(); - result.type = type; - return finishNode(result); - } function parseJSDocTypeReference() { - var result = createNode(259 /* JSDocTypeReference */); + var result = createNode(261 /* JSDocTypeReference */); result.name = parseSimplePropertyName(); while (parseOptional(21 /* DotToken */)) { if (token === 25 /* LessThanToken */) { @@ -11666,7 +11962,7 @@ var ts; return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(257 /* JSDocRecordType */); + var result = createNode(259 /* JSDocRecordType */); nextToken(); result.members = parseDelimitedList(24 /* JSDocRecordMembers */, parseJSDocRecordMember); checkForTrailingComma(result.members); @@ -11674,7 +11970,7 @@ var ts; return finishNode(result); } function parseJSDocRecordMember() { - var result = createNode(258 /* JSDocRecordMember */); + var result = createNode(260 /* JSDocRecordMember */); result.name = parseSimplePropertyName(); if (token === 54 /* ColonToken */) { nextToken(); @@ -11683,13 +11979,13 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(256 /* JSDocNonNullableType */); + var result = createNode(258 /* JSDocNonNullableType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(254 /* JSDocTupleType */); + var result = createNode(256 /* JSDocTupleType */); nextToken(); result.types = parseDelimitedList(25 /* JSDocTupleTypes */, parseJSDocType); checkForTrailingComma(result.types); @@ -11703,7 +11999,7 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(253 /* JSDocUnionType */); + var result = createNode(255 /* JSDocUnionType */); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); parseExpected(18 /* CloseParenToken */); @@ -11721,7 +12017,7 @@ var ts; return types; } function parseJSDocAllType() { - var result = createNode(250 /* JSDocAllType */); + var result = createNode(252 /* JSDocAllType */); nextToken(); return finishNode(result); } @@ -11744,11 +12040,11 @@ var ts; token === 27 /* GreaterThanToken */ || token === 56 /* EqualsToken */ || token === 47 /* BarToken */) { - var result = createNode(251 /* JSDocUnknownType */, pos); + var result = createNode(253 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(255 /* JSDocNullableType */, pos); + var result = createNode(257 /* JSDocNullableType */, pos); result.type = parseJSDocType(); return finishNode(result); } @@ -11836,7 +12132,7 @@ var ts; if (!tags) { return undefined; } - var result = createNode(265 /* JSDocComment */, start); + var result = createNode(267 /* JSDocComment */, start); result.tags = tags; return finishNode(result, end); } @@ -11873,7 +12169,7 @@ var ts; return undefined; } function handleUnknownTag(atToken, tagName) { - var result = createNode(266 /* JSDocTag */, atToken.pos); + var result = createNode(268 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result, pos); @@ -11924,7 +12220,7 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(267 /* JSDocParameterTag */, atToken.pos); + var result = createNode(269 /* JSDocParameterTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; @@ -11934,27 +12230,27 @@ var ts; return finishNode(result, pos); } function handleReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 268 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 270 /* JSDocReturnTag */; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(268 /* JSDocReturnTag */, atToken.pos); + var result = createNode(270 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result, pos); } function handleTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 269 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 271 /* JSDocTypeTag */; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(269 /* JSDocTypeTag */, atToken.pos); + var result = createNode(271 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result, pos); } function handleTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 270 /* JSDocTemplateTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 272 /* JSDocTemplateTag */; })) { parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } var typeParameters = []; @@ -11978,7 +12274,7 @@ var ts; pos++; } typeParameters.end = pos; - var result = createNode(270 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(272 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; @@ -12019,7 +12315,7 @@ var ts; if (sourceFile.statements.length === 0) { // If we don't have any statements in the current source file, then there's no real // way to incrementally parse. So just do a full parse instead. - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setNodeParents*/ true); + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true); } // Make sure we're not trying to incrementally update a source file more than once. Once // we do an update the original source file is considered unusbale from that point onwards. @@ -12075,7 +12371,7 @@ var ts; // inconsistent tree. Setting the parents on the new tree should be very fast. We // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true); + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true); return result; } IncrementalParser.updateSourceFile = updateSourceFile; @@ -12508,16 +12804,16 @@ var ts; function getModuleInstanceState(node) { // A module is uninstantiated if it contains only // 1. interface declarations, type alias declarations - if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 216 /* TypeAliasDeclaration */) { + if (node.kind === 217 /* InterfaceDeclaration */ || node.kind === 218 /* TypeAliasDeclaration */) { return 0 /* NonInstantiated */; } else if (ts.isConstEnumDeclaration(node)) { return 2 /* ConstEnumOnly */; } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) { + else if ((node.kind === 224 /* ImportDeclaration */ || node.kind === 223 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) { return 0 /* NonInstantiated */; } - else if (node.kind === 219 /* ModuleBlock */) { + else if (node.kind === 221 /* ModuleBlock */) { var state = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { @@ -12536,7 +12832,7 @@ var ts; }); return state; } - else if (node.kind === 218 /* ModuleDeclaration */) { + else if (node.kind === 220 /* ModuleDeclaration */) { return getModuleInstanceState(node.body); } else { @@ -12604,6 +12900,8 @@ var ts; file.symbolCount = symbolCount; file.classifiableNames = classifiableNames; } + file = undefined; + options = undefined; parent = undefined; container = undefined; blockScopeContainer = undefined; @@ -12632,20 +12930,25 @@ var ts; if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { symbol.members = {}; } - if (symbolFlags & 107455 /* Value */ && !symbol.valueDeclaration) { - symbol.valueDeclaration = node; + if (symbolFlags & 107455 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 220 /* ModuleDeclaration */)) { + // other kinds of value declarations take precedence over modules + symbol.valueDeclaration = node; + } } } // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { if (node.name) { - if (node.kind === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { + if (node.kind === 220 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { return "\"" + node.name.text + "\""; } if (node.name.kind === 136 /* ComputedPropertyName */) { var nameExpression = node.name.expression; - // treat computed property names where expression is string/numeric literal as just string/numeric literal + // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression.kind)) { return nameExpression.text; } @@ -12665,15 +12968,27 @@ var ts; return "__new"; case 149 /* IndexSignature */: return "__index"; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return "__export"; - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return node.isExportEquals ? "export=" : "default"; - case 181 /* BinaryExpression */: - // Binary expression case is for JS module 'module.exports = expr' - return "export="; - case 213 /* FunctionDeclaration */: - case 214 /* ClassDeclaration */: + case 183 /* BinaryExpression */: + switch (ts.getSpecialPropertyAssignmentKind(node)) { + case 2 /* ModuleExports */: + // module.exports = ... + return "export="; + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + // exports.x = ... or this.y = ... + return node.left.name.text; + case 3 /* PrototypeProperty */: + // className.prototype.methodName = ... + return node.left.expression.name.text; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 215 /* FunctionDeclaration */: + case 216 /* ClassDeclaration */: return node.flags & 512 /* Default */ ? "default" : undefined; } } @@ -12750,7 +13065,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = ts.getCombinedNodeFlags(node) & 2 /* Export */; if (symbolFlags & 8388608 /* Alias */) { - if (node.kind === 230 /* ExportSpecifier */ || (node.kind === 221 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 232 /* ExportSpecifier */ || (node.kind === 223 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -12833,10 +13148,10 @@ var ts; var flags = node.flags; // reset all reachability check related flags on node (for incremental scenarios) flags &= ~1572864 /* ReachabilityCheckFlags */; - if (kind === 215 /* InterfaceDeclaration */) { + if (kind === 217 /* InterfaceDeclaration */) { seenThisKeyword = false; } - var saveState = kind === 248 /* SourceFile */ || kind === 219 /* ModuleBlock */ || ts.isFunctionLikeKind(kind); + var saveState = kind === 250 /* SourceFile */ || kind === 221 /* ModuleBlock */ || ts.isFunctionLikeKind(kind); if (saveState) { savedReachabilityState = currentReachabilityState; savedLabelStack = labelStack; @@ -12854,7 +13169,7 @@ var ts; flags |= 1048576 /* HasExplicitReturn */; } } - if (kind === 215 /* InterfaceDeclaration */) { + if (kind === 217 /* InterfaceDeclaration */) { flags = seenThisKeyword ? flags | 262144 /* ContainsThis */ : flags & ~262144 /* ContainsThis */; } node.flags = flags; @@ -12879,40 +13194,40 @@ var ts; return; } switch (node.kind) { - case 198 /* WhileStatement */: + case 200 /* WhileStatement */: bindWhileStatement(node); break; - case 197 /* DoStatement */: + case 199 /* DoStatement */: bindDoStatement(node); break; - case 199 /* ForStatement */: + case 201 /* ForStatement */: bindForStatement(node); break; - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 196 /* IfStatement */: + case 198 /* IfStatement */: bindIfStatement(node); break; - case 204 /* ReturnStatement */: - case 208 /* ThrowStatement */: + case 206 /* ReturnStatement */: + case 210 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: + case 205 /* BreakStatement */: + case 204 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 209 /* TryStatement */: + case 211 /* TryStatement */: bindTryStatement(node); break; - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: bindSwitchStatement(node); break; - case 220 /* CaseBlock */: + case 222 /* CaseBlock */: bindCaseBlock(node); break; - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: bindLabeledStatement(node); break; default: @@ -12964,7 +13279,7 @@ var ts; popImplicitLabel(postStatementLabel, preStatementState); } function bindIfStatement(n) { - // denotes reachability state when entering 'thenStatement' part of the if statement: + // denotes reachability state when entering 'thenStatement' part of the if statement: // i.e. if condition is false then thenStatement is unreachable var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; // denotes reachability state when entering 'elseStatement': @@ -12987,7 +13302,7 @@ var ts; function bindReturnOrThrow(n) { // bind expression (don't affect reachability) bind(n.expression); - if (n.kind === 204 /* ReturnStatement */) { + if (n.kind === 206 /* ReturnStatement */) { hasExplicitReturn = true; } currentReachabilityState = 4 /* Unreachable */; @@ -12996,7 +13311,7 @@ var ts; // call bind on label (don't affect reachability) bind(n.label); // for continue case touch label so it will be marked a used - var isValidJump = jumpToLabel(n.label, n.kind === 203 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */); + var isValidJump = jumpToLabel(n.label, n.kind === 205 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */); if (isValidJump) { currentReachabilityState = 4 /* Unreachable */; } @@ -13022,7 +13337,7 @@ var ts; // bind expression (don't affect reachability) bind(n.expression); bind(n.caseBlock); - var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242 /* DefaultClause */; }); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 244 /* DefaultClause */; }); // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState; popImplicitLabel(postSwitchLabel, postSwitchState); @@ -13049,37 +13364,37 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: + case 188 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: case 155 /* TypeLiteral */: - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return 1 /* IsContainer */; case 147 /* CallSignature */: case 148 /* ConstructSignature */: case 149 /* IndexSignature */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 152 /* FunctionType */: case 153 /* ConstructorType */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 218 /* ModuleDeclaration */: - case 248 /* SourceFile */: - case 216 /* TypeAliasDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 220 /* ModuleDeclaration */: + case 250 /* SourceFile */: + case 218 /* TypeAliasDeclaration */: return 5 /* IsContainerWithLocals */; - case 244 /* CatchClause */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 220 /* CaseBlock */: + case 246 /* CatchClause */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 222 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 192 /* Block */: + case 194 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Othewise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -13116,18 +13431,18 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 248 /* SourceFile */: + case 250 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 216 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case 155 /* TypeLiteral */: - case 165 /* ObjectLiteralExpression */: - case 215 /* InterfaceDeclaration */: + case 167 /* ObjectLiteralExpression */: + case 217 /* InterfaceDeclaration */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the @@ -13144,10 +13459,10 @@ var ts; case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 216 /* TypeAliasDeclaration */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 218 /* TypeAliasDeclaration */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -13168,11 +13483,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 248 /* SourceFile */ ? node : node.body; - if (body.kind === 248 /* SourceFile */ || body.kind === 219 /* ModuleBlock */) { + var body = node.kind === 250 /* SourceFile */ ? node : node.body; + if (body.kind === 250 /* SourceFile */ || body.kind === 221 /* ModuleBlock */) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 228 /* ExportDeclaration */ || stat.kind === 227 /* ExportAssignment */) { + if (stat.kind === 230 /* ExportDeclaration */ || stat.kind === 229 /* ExportAssignment */) { return true; } } @@ -13256,7 +13571,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */ || prop.kind === 143 /* MethodDeclaration */ + var currentKind = prop.kind === 247 /* PropertyAssignment */ || prop.kind === 248 /* ShorthandPropertyAssignment */ || prop.kind === 143 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen[identifier.text]; @@ -13278,10 +13593,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 248 /* SourceFile */: + case 250 /* SourceFile */: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -13441,17 +13756,17 @@ var ts; } function updateStrictMode(node) { switch (node.kind) { - case 248 /* SourceFile */: - case 219 /* ModuleBlock */: + case 250 /* SourceFile */: + case 221 /* ModuleBlock */: updateStrictModeStatementList(node.statements); return; - case 192 /* Block */: + case 194 /* Block */: if (ts.isFunctionLike(node.parent)) { updateStrictModeStatementList(node.statements); } return; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return; @@ -13481,45 +13796,61 @@ var ts; /* Strict mode checks */ case 69 /* Identifier */: return checkStrictModeIdentifier(node); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: if (ts.isInJavaScriptFile(node)) { - if (ts.isExportsPropertyAssignment(node)) { - bindExportsPropertyAssignment(node); - } - else if (ts.isModuleExportsAssignment(node)) { - bindModuleExportsAssignment(node); + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); } } return checkStrictModeBinaryExpression(node); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return checkStrictModeCatchClause(node); - case 175 /* DeleteExpression */: + case 177 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 180 /* PostfixUnaryExpression */: + case 182 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 205 /* WithStatement */: + case 207 /* WithStatement */: return checkStrictModeWithStatement(node); - case 97 /* ThisKeyword */: + case 161 /* ThisType */: seenThisKeyword = true; return; + case 150 /* TypePredicate */: + return checkTypePredicate(node); case 137 /* TypeParameter */: return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); case 138 /* Parameter */: return bindParameter(node); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: return bindVariableDeclarationOrBindingElement(node); case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); - case 245 /* PropertyAssignment */: - case 246 /* ShorthandPropertyAssignment */: + case 247 /* PropertyAssignment */: + case 248 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); - case 247 /* EnumMember */: + case 249 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); case 147 /* CallSignature */: case 148 /* ConstructSignature */: @@ -13532,7 +13863,7 @@ var ts; // so that it will conflict with any other object literal members with the same // name. return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */); - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: checkStrictModeFunctionName(node); return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); case 144 /* Constructor */: @@ -13546,46 +13877,56 @@ var ts; return bindFunctionOrConstructorType(node); case 155 /* TypeLiteral */: return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: checkStrictModeFunctionName(node); var bindingName = node.name ? node.name.text : "__function"; return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); - case 168 /* CallExpression */: + case 170 /* CallExpression */: if (ts.isInJavaScriptFile(node)) { bindCallExpression(node); } break; // Members of classes, interfaces, and modules - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 216 /* ClassDeclaration */: return bindClassLikeDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); - case 216 /* TypeAliasDeclaration */: + case 218 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Imports and exports - case 221 /* ImportEqualsDeclaration */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 223 /* ImportEqualsDeclaration */: + case 226 /* NamespaceImport */: + case 228 /* ImportSpecifier */: + case 232 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - case 223 /* ImportClause */: + case 225 /* ImportClause */: return bindImportClause(node); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return bindExportDeclaration(node); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return bindExportAssignment(node); - case 248 /* SourceFile */: + case 250 /* SourceFile */: return bindSourceFileIfExternalModule(); } } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 69 /* Identifier */) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 161 /* ThisType */) { + seenThisKeyword = true; + } + bind(type); + } function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (ts.isExternalModule(file)) { @@ -13596,7 +13937,7 @@ var ts; bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); } function bindExportAssignment(node) { - var boundExpression = node.kind === 227 /* ExportAssignment */ ? node.expression : node.right; + var boundExpression = node.kind === 229 /* 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)); @@ -13642,6 +13983,29 @@ var ts; setCommonJsModuleIndicator(node); bindExportAssignment(node); } + function bindThisPropertyAssignment(node) { + // Declare a 'member' in case it turns out the container was an ES5 class + if (container.kind === 175 /* FunctionExpression */ || container.kind === 215 /* FunctionDeclaration */) { + container.symbol.members = container.symbol.members || {}; + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); + } + } + 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. + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classId = node.left.expression.expression; + var funcSymbol = container.locals[classId.text]; + if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */)) { + return; + } + // Set up the members collection if it doesn't exist already + if (!funcSymbol.members) { + funcSymbol.members = {}; + } + // Declare the method/property + declareSymbol(funcSymbol.members, funcSymbol, node.left, 4 /* Property */, 107455 /* PropertyExcludes */); + } function bindCallExpression(node) { // We're only inspecting call expressions to detect CommonJS modules, so we can skip // this check if we've already seen the module indicator @@ -13650,7 +14014,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); } else { @@ -13725,9 +14089,7 @@ var ts; } // If this is a property-parameter, then also declare the property symbol into the // containing class. - if (node.flags & 56 /* AccessibilityModifier */ && - node.parent.kind === 144 /* Constructor */ && - ts.isClassLike(node.parent.parent)) { + if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); } @@ -13797,18 +14159,18 @@ var ts; case 4 /* Unreachable */: var reportError = // report error on all statements except empty ones - (ts.isStatement(node) && node.kind !== 194 /* EmptyStatement */) || + (ts.isStatement(node) && node.kind !== 196 /* EmptyStatement */) || // report error on class declarations - node.kind === 214 /* ClassDeclaration */ || + node.kind === 216 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 218 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 220 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 217 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + (node.kind === 219 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentReachabilityState = 8 /* ReportedUnreachable */; // unreachable code is reported if // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error + // - statement is in not ambient context (statements in ambient context is already an error // so we should not report extras) AND // - node is not variable statement OR // - node is block scoped variable statement OR @@ -13817,7 +14179,7 @@ var ts; // On the other side we do want to report errors on non-initialized 'lets' because of TDZ var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && - (node.kind !== 193 /* VariableStatement */ || + (node.kind !== 195 /* VariableStatement */ || ts.getCombinedNodeFlags(node.declarationList) & 24576 /* BlockScoped */ || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { @@ -13853,15 +14215,18 @@ var ts; var nextNodeId = 1; var nextMergeId = 1; function getNodeId(node) { - if (!node.id) - node.id = nextNodeId++; + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } return node.id; } ts.getNodeId = getNodeId; ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { - symbol.id = nextSymbolId++; + symbol.id = nextSymbolId; + nextSymbolId++; } return symbol.id; } @@ -13887,8 +14252,10 @@ var ts; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0 /* ES3 */; var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === 4 /* System */; var emitResolver = createResolver(); var undefinedSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "undefined"); + undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -13902,6 +14269,7 @@ var ts; // The language service will always care about the narrowed type of a symbol, because that is // the type the language says the symbol should have. getTypeOfSymbolAtLocation: getNarrowedTypeOfSymbol, + getSymbolsOfParameterPropertyDeclaration: getSymbolsOfParameterPropertyDeclaration, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: getPropertyOfType, @@ -13918,7 +14286,7 @@ var ts; symbolToString: symbolToString, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: getApparentTypeOfContextualType, + getContextualType: getContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: getResolvedSignature, getConstantValue: getConstantValue, @@ -13943,8 +14311,8 @@ var ts; var undefinedType = createIntrinsicType(32 /* Undefined */ | 2097152 /* ContainsUndefinedOrNull */, "undefined"); var nullType = createIntrinsicType(64 /* Null */ | 2097152 /* ContainsUndefinedOrNull */, "null"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var circularType = createIntrinsicType(1 /* Any */, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyUnionType = emptyObjectType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -13952,8 +14320,8 @@ var ts; // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); var globals = {}; var globalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; @@ -13966,9 +14334,6 @@ var ts; var globalRegExpType; var globalTemplateStringsArrayType; var globalESSymbolType; - var jsxElementType; - /** Lazily loaded, use getJsxIntrinsicElementType() */ - var jsxIntrinsicElementsType; var globalIterableType; var globalIteratorType; var globalIterableIteratorType; @@ -13985,6 +14350,7 @@ var ts; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; var jsxElementClassType; + var deferredNodes; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; @@ -14019,14 +14385,23 @@ var ts; "symbol": { type: esSymbolType, flags: 16777216 /* ESSymbol */ + }, + "undefined": { + type: undefinedType, + flags: 2097152 /* ContainsUndefinedOrNull */ } }; + var jsxElementType; + /** Things we lazy load from the JSX namespace */ + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", ElementClass: "ElementClass", ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - Element: "Element" + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" }; var subtypeRelation = {}; var assignableRelation = {}; @@ -14040,6 +14415,10 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -14095,8 +14474,10 @@ var ts; return result; } function recordMergedSymbol(target, source) { - if (!source.mergeId) - source.mergeId = nextMergeId++; + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { @@ -14121,8 +14502,12 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (!target.valueDeclaration && source.valueDeclaration) + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 220 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 220 /* ModuleDeclaration */))) { + // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; + } ts.forEach(source.declarations, function (node) { target.declarations.push(node); }); @@ -14174,6 +14559,22 @@ 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]; + } + } + } + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } function getSymbolLinks(symbol) { if (symbol.flags & 67108864 /* Transient */) return symbol; @@ -14185,10 +14586,17 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } function getSourceFile(node) { - return ts.getAncestor(node, 248 /* SourceFile */); + return ts.getAncestor(node, 250 /* SourceFile */); } function isGlobalSourceFile(node) { - return node.kind === 248 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 250 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + } + /** Is this type one of the apparent types created from the primitive types. */ + function isPrimitiveApparentType(type) { + return type === globalStringType || + type === globalNumberType || + type === globalBooleanType || + type === globalESSymbolType; } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -14207,6 +14615,22 @@ var ts; } // return undefined if we can't find a symbol. } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructoDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructoDeclaration.locals, parameterName, 107455 /* Value */); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); @@ -14221,7 +14645,7 @@ var ts; if (declaration.pos <= usage.pos) { // declaration is before usage // still might be illegal if usage is in the initializer of the variable declaration - return declaration.kind !== 211 /* VariableDeclaration */ || + return declaration.kind !== 213 /* VariableDeclaration */ || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } // declaration is after usage @@ -14229,14 +14653,14 @@ var ts; return isUsedInFunctionOrNonStaticProperty(declaration, usage); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); - if (declaration.parent.parent.kind === 193 /* VariableStatement */ || - declaration.parent.parent.kind === 199 /* ForStatement */) { + if (declaration.parent.parent.kind === 195 /* VariableStatement */ || + declaration.parent.parent.kind === 201 /* ForStatement */) { // variable statement/for statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) return isSameScopeDescendentOf(usage, declaration, container); } - else if (declaration.parent.parent.kind === 201 /* ForOfStatement */ || - declaration.parent.parent.kind === 200 /* ForInStatement */) { + else if (declaration.parent.parent.kind === 203 /* ForOfStatement */ || + declaration.parent.parent.kind === 202 /* ForInStatement */) { // ForIn/ForOf case - use site should not be used in expression part var expression = declaration.parent.parent.expression; return isSameScopeDescendentOf(usage, expression, container); @@ -14277,25 +14701,46 @@ var ts; // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { - // Type parameters of a function are in scope in the entire function declaration, including the parameter - // list and return type. However, local types are only in scope in the function body. - if (!(meaning & 793056 /* Type */) || - !(result.flags & (793056 /* Type */ & ~262144 /* TypeParameter */)) || - !ts.isFunctionLike(location) || - lastLocation === location.body) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + if (meaning & result.flags & 793056 /* Type */) { + useResult = result.flags & 262144 /* TypeParameter */ + ? lastLocation === location.type || + lastLocation.kind === 138 /* Parameter */ || + lastLocation.kind === 137 /* TypeParameter */ + : false; + } + if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 138 /* Parameter */ || + (lastLocation === location.type && + result.valueDeclaration.kind === 138 /* Parameter */); + } + } + if (useResult) { break loop; } - result = undefined; + else { + result = undefined; + } } } switch (location.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 248 /* SourceFile */ || - (location.kind === 218 /* ModuleDeclaration */ && location.name.kind === 9 /* StringLiteral */)) { + if (location.kind === 250 /* SourceFile */ || + (location.kind === 220 /* ModuleDeclaration */ && location.name.kind === 9 /* StringLiteral */)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports["default"]) { @@ -14306,7 +14751,7 @@ var ts; result = undefined; } // Because of module/namespace merging, a module's exports are in scope, - // yet we never want to treat an export specifier as putting a member in scope. + // yet we never want to treat an export specifier as putting a member in scope. // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. // Two things to note about this: // 1. We have to check this without calling getSymbol. The problem with calling getSymbol @@ -14318,7 +14763,7 @@ var ts; // which is not the desired behavior. if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 /* Alias */ && - ts.getDeclarationOfKind(moduleExports[name], 230 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExports[name], 232 /* ExportSpecifier */)) { break; } } @@ -14326,7 +14771,7 @@ var ts; break loop; } break; - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } @@ -14349,9 +14794,9 @@ var ts; } } break; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 217 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { if (lastLocation && lastLocation.flags & 64 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 @@ -14362,7 +14807,7 @@ var ts; } break loop; } - if (location.kind === 186 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 188 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -14380,7 +14825,7 @@ var ts; // case 136 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 215 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 217 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -14393,14 +14838,14 @@ var ts; case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + case 176 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 173 /* FunctionExpression */: + case 175 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -14482,7 +14927,7 @@ var ts; // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 211 /* VariableDeclaration */), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 213 /* VariableDeclaration */), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -14503,10 +14948,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 223 /* ImportEqualsDeclaration */) { return node; } - while (node && node.kind !== 222 /* ImportDeclaration */) { + while (node && node.kind !== 224 /* ImportDeclaration */) { node = node.parent; } return node; @@ -14516,7 +14961,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 232 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 234 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -14525,9 +14970,12 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); - if (!exportDefaultSymbol) { + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveSymbol(moduleSymbol.exports["export="]) || resolveSymbol(moduleSymbol); + } return exportDefaultSymbol; } } @@ -14535,14 +14983,6 @@ var ts; var moduleSpecifier = node.parent.parent.moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } - function getMemberOfModuleVariable(moduleSymbol, name) { - if (moduleSymbol.flags & 3 /* Variable */) { - var typeAnnotation = moduleSymbol.valueDeclaration.type; - if (typeAnnotation) { - return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); - } - } - } // This function creates a synthetic symbol that combines the value side of one symbol with the // type/namespace side of another symbol. Consider this example: // @@ -14623,17 +15063,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node); - case 223 /* ImportClause */: + case 225 /* ImportClause */: return getTargetOfImportClause(node); - case 224 /* NamespaceImport */: + case 226 /* NamespaceImport */: return getTargetOfNamespaceImport(node); - case 226 /* ImportSpecifier */: + case 228 /* ImportSpecifier */: return getTargetOfImportSpecifier(node); - case 230 /* ExportSpecifier */: + case 232 /* ExportSpecifier */: return getTargetOfExportSpecifier(node); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return getTargetOfExportAssignment(node); } } @@ -14678,11 +15118,11 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 227 /* ExportAssignment */) { + if (node.kind === 229 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 230 /* ExportSpecifier */) { + else if (node.kind === 232 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -14695,7 +15135,7 @@ var ts; // This function is only for imports with entity names function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 221 /* ImportEqualsDeclaration */); + importDeclaration = ts.getAncestor(entityName, 223 /* ImportEqualsDeclaration */); ts.Debug.assert(importDeclaration !== undefined); } // There are three things we might try to look for. In the following examples, @@ -14714,7 +15154,7 @@ var ts; else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 221 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 223 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); } } @@ -14734,7 +15174,7 @@ var ts; return undefined; } } - else if (name.kind === 135 /* QualifiedName */ || name.kind === 166 /* PropertyAccessExpression */) { + else if (name.kind === 135 /* QualifiedName */ || name.kind === 168 /* PropertyAccessExpression */) { var left = name.kind === 135 /* QualifiedName */ ? name.left : name.expression; var right = name.kind === 135 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors); @@ -14760,16 +15200,12 @@ var ts; return; } var moduleReferenceLiteral = moduleReferenceExpression; - var searchPath = ts.getDirectoryPath(getSourceFile(location).fileName); // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); if (moduleName === undefined) { return; } - if (moduleName.indexOf("!") >= 0) { - moduleName = moduleName.substr(0, moduleName.indexOf("!")); - } var isRelative = ts.isExternalModuleNameRelative(moduleName); if (!isRelative) { var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); @@ -14817,38 +15253,66 @@ var ts; var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } - function extendExportSymbols(target, source) { + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; + if (lookupTable && exportNode) { + lookupTable[id] = { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }; + } + } + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + if (!lookupTable[id].exportsWithDuplicate) { + lookupTable[id].exportsWithDuplicate = [exportNode]; + } + else { + lookupTable[id].exportsWithDuplicate.push(exportNode); + } } } } function getExportsForModule(moduleSymbol) { - var result; var visitedSymbols = []; - visit(moduleSymbol); - return result || moduleSymbol.exports; + return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. function visit(symbol) { - if (symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol)) { - visitedSymbols.push(symbol); - if (symbol !== moduleSymbol) { - if (!result) { - result = cloneSymbolTable(moduleSymbol.exports); - } - extendExportSymbols(result, symbol.exports); - } - // All export * declarations are collected in an __export symbol by the binder - var exportStars = symbol.exports["__export"]; - if (exportStars) { - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - visit(resolveExternalModuleName(node, node.moduleSpecifier)); - } - } + if (!(symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol))) { + return; } + visitedSymbols.push(symbol); + var symbols = cloneSymbolTable(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 = {}; + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node); + } + 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)) { + continue; + } + for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { + var node = exportsWithDuplicate_1[_b]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable[id].specifierText, id)); + } + } + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; } } function getMergedSymbol(symbol) { @@ -14893,7 +15357,8 @@ var ts; } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount++; + result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -14956,17 +15421,17 @@ var ts; } } switch (location_1.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -15007,7 +15472,7 @@ var ts; return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 /* Alias */ && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230 /* ExportSpecifier */)) { + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 232 /* ExportSpecifier */)) { if (!useOnlyExternalAliasing || // Is this external alias, then use it to name ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { @@ -15044,7 +15509,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 232 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -15117,8 +15582,8 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 218 /* ModuleDeclaration */ && declaration.name.kind === 9 /* StringLiteral */) || - (declaration.kind === 248 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return (declaration.kind === 220 /* ModuleDeclaration */ && declaration.name.kind === 9 /* StringLiteral */) || + (declaration.kind === 250 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -15158,8 +15623,8 @@ var ts; // Typeof value meaning = 107455 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 135 /* QualifiedName */ || entityName.kind === 166 /* PropertyAccessExpression */ || - entityName.parent.kind === 221 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 135 /* QualifiedName */ || entityName.kind === 168 /* PropertyAccessExpression */ || + entityName.parent.kind === 223 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1536 /* Namespace */; @@ -15193,9 +15658,9 @@ var ts; ts.releaseStringWriter(writer); return result; } - function signatureToString(signature, enclosingDeclaration, flags) { + function signatureToString(signature, enclosingDeclaration, flags, kind) { var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); var result = writer.string(); ts.releaseStringWriter(writer); return result; @@ -15217,7 +15682,7 @@ var ts; while (node.kind === 160 /* ParenthesizedType */) { node = node.parent; } - if (node.kind === 216 /* TypeAliasDeclaration */) { + if (node.kind === 218 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -15231,10 +15696,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: return "(Anonymous class)"; - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return "(Anonymous function)"; } } @@ -15322,10 +15787,16 @@ var ts; function writeType(type, flags) { // Write undefined/null type as any if (type.flags & 16777343 /* 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); + if (type.flags & 134217728 /* PredicateType */) { + buildTypePredicateDisplay(writer, type.predicate); + buildTypeDisplay(type.predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } + else { + // 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 */) { if (inObjectTypeLiteral) { @@ -15381,11 +15852,13 @@ var ts; } if (pos < end) { writePunctuation(writer, 25 /* LessThanToken */); - writeType(typeArguments[pos++], 0 /* None */); + writeType(typeArguments[pos], 0 /* None */); + pos++; while (pos < end) { writePunctuation(writer, 24 /* CommaToken */); writeSpace(writer); - writeType(typeArguments[pos++], 0 /* None */); + writeType(typeArguments[pos], 0 /* None */); + pos++; } writePunctuation(writer, 27 /* GreaterThanToken */); } @@ -15481,7 +15954,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 248 /* SourceFile */ || declaration.parent.kind === 219 /* ModuleBlock */; + return declaration.parent.kind === 250 /* SourceFile */ || declaration.parent.kind === 221 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -15517,7 +15990,7 @@ var ts; if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* OpenParenToken */); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -15529,7 +16002,7 @@ var ts; } writeKeyword(writer, 92 /* NewKeyword */); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -15543,15 +16016,13 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - writeKeyword(writer, 92 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } @@ -15594,7 +16065,7 @@ var ts; if (p.flags & 536870912 /* Optional */) { writePunctuation(writer, 53 /* QuestionToken */); } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } @@ -15682,6 +16153,17 @@ var ts; } writePunctuation(writer, 18 /* CloseParenToken */); } + function buildTypePredicateDisplay(writer, predicate) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 97 /* ThisKeyword */); + } + writeSpace(writer); + writeKeyword(writer, 124 /* IsKeyword */); + writeSpace(writer); + } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8 /* WriteArrowStyleSignature */) { writeSpace(writer); @@ -15691,20 +16173,14 @@ var ts; writePunctuation(writer, 54 /* ColonToken */); } writeSpace(writer); - var returnType; - if (signature.typePredicate) { - writer.writeParameter(signature.typePredicate.parameterName); - writeSpace(writer); - writeKeyword(writer, 124 /* IsKeyword */); - writeSpace(writer); - returnType = signature.typePredicate.type; - } - else { - returnType = getReturnTypeOfSignature(signature); - } + var returnType = getReturnTypeOfSignature(signature); buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1 /* Construct */) { + writeKeyword(writer, 92 /* NewKeyword */); + writeSpace(writer); + } if (signature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */)) { // Instantiated signature, write type arguments instead // This is achieved by passing in the mapper separately @@ -15729,82 +16205,36 @@ var ts; }); } function isDeclarationVisible(node) { - function getContainingExternalModule(node) { - for (; node; node = node.parent) { - if (node.kind === 218 /* ModuleDeclaration */) { - if (node.name.kind === 9 /* StringLiteral */) { - return node; - } - } - else if (node.kind === 248 /* SourceFile */) { - return ts.isExternalOrCommonJsModule(node) ? node : undefined; - } - } - ts.Debug.fail("getContainingModule cant reach here"); - } - function isUsedInExportAssignment(node) { - // Get source File and see if it is external module and has export assigned symbol - var externalModule = getContainingExternalModule(node); - var exportAssignmentSymbol; - var resolvedExportSymbol; - if (externalModule) { - // This is export assigned symbol node - var externalModuleSymbol = getSymbolOfNode(externalModule); - exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); - var symbolOfNode = getSymbolOfNode(node); - if (isSymbolUsedInExportAssignment(symbolOfNode)) { - return true; - } - // if symbolOfNode is alias declaration, resolve the symbol declaration and check - if (symbolOfNode.flags & 8388608 /* Alias */) { - return isSymbolUsedInExportAssignment(resolveAlias(symbolOfNode)); - } - } - // Check if the symbol is used in export assignment - function isSymbolUsedInExportAssignment(symbol) { - if (exportAssignmentSymbol === symbol) { - return true; - } - if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 8388608 /* Alias */)) { - // if export assigned symbol is alias declaration, resolve the alias - resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol); - if (resolvedExportSymbol === symbol) { - return true; - } - // Container of resolvedExportSymbol is visible - return ts.forEach(resolvedExportSymbol.declarations, function (current) { - while (current) { - if (current === node) { - return true; - } - current = current.parent; - } - }); - } + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); } + return links.isVisible; } + return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 163 /* BindingElement */: + case 165 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // Otherwise fall through - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 213 /* FunctionDeclaration */: - case 217 /* EnumDeclaration */: - case 221 /* ImportEqualsDeclaration */: + case 220 /* ModuleDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 215 /* FunctionDeclaration */: + case 219 /* EnumDeclaration */: + case 223 /* ImportEqualsDeclaration */: var parent_4 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedNodeFlags(node) & 2 /* Export */) && - !(node.kind !== 221 /* ImportEqualsDeclaration */ && parent_4.kind !== 248 /* SourceFile */ && ts.isInAmbientContext(parent_4))) { + !(node.kind !== 223 /* ImportEqualsDeclaration */ && parent_4.kind !== 250 /* SourceFile */ && ts.isInAmbientContext(parent_4))) { return isGlobalSourceFile(parent_4); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible @@ -15825,7 +16255,7 @@ var ts; case 147 /* CallSignature */: case 149 /* IndexSignature */: case 138 /* Parameter */: - case 219 /* ModuleBlock */: + case 221 /* ModuleBlock */: case 152 /* FunctionType */: case 153 /* ConstructorType */: case 155 /* TypeLiteral */: @@ -15838,36 +16268,29 @@ var ts; return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: + case 225 /* ImportClause */: + case 226 /* NamespaceImport */: + case 228 /* ImportSpecifier */: return false; // Type parameters are always visible case 137 /* TypeParameter */: // Source file is always visible - case 248 /* SourceFile */: + case 250 /* SourceFile */: return true; // Export assignments do not create name bindings outside the module - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return false; default: ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); } } - if (node) { - var links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 227 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 229 /* ExportAssignment */) { exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 230 /* ExportSpecifier */) { + else if (node.parent.kind === 232 /* ExportSpecifier */) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -15917,7 +16340,7 @@ var ts; return false; } resolutionTargets.push(target); - resolutionResults.push(true); + resolutionResults.push(/*items*/ true); resolutionPropertyNames.push(propertyName); return true; } @@ -15959,7 +16382,7 @@ var ts; node = ts.getRootDeclaration(node); // Parent chain: // VaribleDeclaration -> VariableDeclarationList -> VariableStatement -> 'Declaration Container' - return node.kind === 211 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; + return node.kind === 213 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; } function getTypeOfPrototypeProperty(prototype) { // TypeScript 1.0 spec (April 2014): 8.4 @@ -16018,7 +16441,7 @@ var ts; return parentType; } var type; - if (pattern.kind === 161 /* ObjectBindingPattern */) { + if (pattern.kind === 163 /* ObjectBindingPattern */) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name_10 = declaration.propertyName || declaration.name; if (isComputedNonLiteralName(name_10)) { @@ -16067,10 +16490,10 @@ var ts; // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration) { // A variable declared in a for..in statement is always of type any - if (declaration.parent.parent.kind === 200 /* ForInStatement */) { + if (declaration.parent.parent.kind === 202 /* ForInStatement */) { return anyType; } - if (declaration.parent.parent.kind === 201 /* ForOfStatement */) { + if (declaration.parent.parent.kind === 203 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -16104,7 +16527,7 @@ var ts; return checkExpressionCached(declaration.initializer); } // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 246 /* ShorthandPropertyAssignment */) { + if (declaration.kind === 248 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } // If the declaration specifies a binding pattern, use the type implied by the binding pattern @@ -16160,7 +16583,7 @@ var ts; 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 === 187 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return e.kind === 189 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { var result = createNewTupleType(elementTypes); result.pattern = pattern; @@ -16176,7 +16599,7 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType) { - return pattern.kind === 161 /* ObjectBindingPattern */ + return pattern.kind === 163 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType) : getTypeFromArrayBindingPattern(pattern, includePatternInType); } @@ -16198,7 +16621,13 @@ var ts; // During a normal type check we'll never get to here with a property assignment (the check of the containing // object literal uses a different path). We exclude widening only so that language services and type verification // tools see the actual type. - return declaration.kind !== 245 /* PropertyAssignment */ ? getWidenedType(type) : type; + if (declaration.kind === 247 /* PropertyAssignment */) { + return type; + } + if (type.flags & 134217728 /* PredicateType */ && (declaration.kind === 141 /* PropertyDeclaration */ || declaration.kind === 140 /* PropertySignature */)) { + return type; + } + return getWidenedType(type); } // Rest parameters default to type any[], other parameters default to type any type = declaration.dotDotDotToken ? anyArrayType : anyType; @@ -16220,20 +16649,24 @@ var ts; } // Handle catch clause variables var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 244 /* CatchClause */) { + if (declaration.parent.kind === 246 /* CatchClause */) { return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 227 /* ExportAssignment */) { + if (declaration.kind === 229 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } // Handle module.exports = expr - if (declaration.kind === 181 /* BinaryExpression */) { + if (declaration.kind === 183 /* BinaryExpression */) { return links.type = checkExpression(declaration.right); } - // Handle exports.p = expr - if (declaration.kind === 166 /* PropertyAccessExpression */) { - return checkExpressionCached(declaration.parent.right); + if (declaration.kind === 168 /* PropertyAccessExpression */) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === 183 /* BinaryExpression */) { + // Handle exports.p = expr or this.p = expr or className.prototype.method = expr + return links.type = checkExpressionCached(declaration.parent.right); + } } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { @@ -16406,9 +16839,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 214 /* ClassDeclaration */ || node.kind === 186 /* ClassExpression */ || - node.kind === 213 /* FunctionDeclaration */ || node.kind === 173 /* FunctionExpression */ || - node.kind === 143 /* MethodDeclaration */ || node.kind === 174 /* ArrowFunction */) { + if (node.kind === 216 /* ClassDeclaration */ || node.kind === 188 /* ClassExpression */ || + node.kind === 215 /* FunctionDeclaration */ || node.kind === 175 /* FunctionExpression */ || + node.kind === 143 /* MethodDeclaration */ || node.kind === 176 /* ArrowFunction */) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -16418,7 +16851,7 @@ var ts; } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 215 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 217 /* InterfaceDeclaration */); return appendOuterTypeParameters(undefined, declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -16427,8 +16860,8 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 214 /* ClassDeclaration */ || - node.kind === 186 /* ClassExpression */ || node.kind === 216 /* TypeAliasDeclaration */) { + if (node.kind === 217 /* InterfaceDeclaration */ || node.kind === 216 /* ClassDeclaration */ || + node.kind === 188 /* ClassExpression */ || node.kind === 218 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -16492,9 +16925,6 @@ var ts; } return type.resolvedBaseConstructorType; } - function hasClassBaseType(type) { - return !!ts.forEach(getBaseTypes(type), function (t) { return !!(t.symbol.flags & 32 /* Class */); }); - } function getBaseTypes(type) { var isClass = type.symbol.flags & 32 /* Class */; var isInterface = type.symbol.flags & 64 /* Interface */; @@ -16571,7 +17001,7 @@ var ts; type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 217 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -16603,7 +17033,7 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 /* InterfaceDeclaration */) { + if (declaration.kind === 217 /* InterfaceDeclaration */) { if (declaration.flags & 262144 /* ContainsThis */) { return false; } @@ -16659,7 +17089,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 216 /* TypeAliasDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 218 /* TypeAliasDeclaration */); var type = getTypeFromTypeNode(declaration.type); if (popTypeResolution()) { links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -16748,7 +17178,7 @@ var ts; case 120 /* BooleanKeyword */: case 131 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 9 /* StringLiteral */: + case 162 /* StringLiteralType */: return true; case 156 /* ArrayType */: return isIndependentType(node.elementType); @@ -16824,14 +17254,6 @@ var ts; } } } - function addInheritedSignatures(signatures, baseSignatures) { - if (baseSignatures) { - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var signature = baseSignatures_1[_i]; - signatures.push(signature); - } - } - } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; @@ -16892,33 +17314,32 @@ var ts; type.typeArguments : ts.concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration, typeParameters, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { + function createSignature(declaration, typeParameters, parameters, resolvedReturnType, minArgumentCount, hasRestParameter, hasStringLiterals) { var sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasStringLiterals = hasStringLiterals; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - if (!hasClassBaseType(classType)) { - return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; + } var baseTypeNode = getBaseTypeNodeOfClass(classType); var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { - var baseSig = baseSignatures_2[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -16949,7 +17370,7 @@ var ts; function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreReturnTypes, compareTypesIdentical)) { return s; } } @@ -17052,36 +17473,29 @@ var ts; } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; - var members; - var callSignatures; - var constructSignatures; - var stringIndexType; - var numberIndexType; if (type.target) { - members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); - callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); - constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); - stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0 /* String */), type.mapper); - numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1 /* Number */), type.mapper); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); + var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); + var stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0 /* String */), type.mapper); + var numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1 /* Number */), type.mapper); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } else if (symbol.flags & 2048 /* TypeLiteral */) { - members = symbol.members; - callSignatures = getSignaturesOfSymbol(members["__call"]); - constructSignatures = getSignaturesOfSymbol(members["__new"]); - stringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); - numberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members["__call"]); + var constructSignatures = getSignaturesOfSymbol(members["__new"]); + var stringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); + var numberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } else { // Combinations of function, class, enum and module - members = emptySymbols; - callSignatures = emptyArray; - constructSignatures = emptyArray; + var members = emptySymbols; + var constructSignatures = emptyArray; if (symbol.flags & 1952 /* HasExports */) { members = getExportsOfSymbol(symbol); } - if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { - callSignatures = getSignaturesOfSymbol(symbol); - } if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); @@ -17094,10 +17508,16 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } - stringIndexType = undefined; - numberIndexType = (symbol.flags & 384 /* Enum */) ? stringType : undefined; + var numberIndexType = (symbol.flags & 384 /* Enum */) ? stringType : undefined; + setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexType); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -17122,15 +17542,15 @@ var ts; } return type; } - // Return properties of an object type or an empty array for other types + /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { if (type.flags & 80896 /* ObjectType */) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } - // 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. + /** 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 */) { var resolved = resolveStructuredTypeMembers(type); @@ -17201,12 +17621,15 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { 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 */; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 /* Private */ | 32 /* Protected */))) { + commonFlags &= prop.flags; if (!props) { props = [prop]; } @@ -17235,7 +17658,10 @@ var ts; } propTypes.push(getTypeOfSymbol(prop)); } - var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */, name); + var result = createSymbol(4 /* Property */ | + 67108864 /* Transient */ | + 268435456 /* SyntheticProperty */ | + commonFlags, name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & 16384 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -17292,22 +17718,6 @@ var ts; function getSignaturesOfType(type, kind) { return getSignaturesOfStructuredType(getApparentType(type), kind); } - function typeHasConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & (80896 /* ObjectType */ | 16384 /* Union */)) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.constructSignatures.length > 0; - } - return false; - } - function typeHasCallOrConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & 130048 /* StructuredType */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; - } - return false; - } function getIndexTypeOfStructuredType(type, kind) { if (type.flags & 130048 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); @@ -17353,6 +17763,23 @@ var ts; } return false; } + function createTypePredicateFromTypePredicateNode(node) { + if (node.parameterName.kind === 69 /* Identifier */) { + var parameterName = node.parameterName; + return { + kind: 1 /* Identifier */, + parameterName: parameterName ? parameterName.text : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0 /* This */, + type: getTypeFromTypeNode(node.type) + }; + } + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { @@ -17366,8 +17793,14 @@ var ts; var minArgumentCount = -1; for (var i = 0, n = declaration.parameters.length; i < n; i++) { var param = declaration.parameters[i]; - parameters.push(param.symbol); - if (param.type && param.type.kind === 9 /* StringLiteral */) { + var paramSymbol = param.symbol; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.name, 107455 /* Value */, undefined, undefined); + paramSymbol = resolvedSymbol; + } + parameters.push(paramSymbol); + if (param.type && param.type.kind === 162 /* StringLiteralType */) { hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken) { @@ -17384,20 +17817,11 @@ var ts; minArgumentCount = declaration.parameters.length; } var returnType; - var typePredicate; if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); - if (declaration.type.kind === 150 /* TypePredicate */) { - var typePredicateNode = declaration.type; - typePredicate = { - parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, - parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, - type: getTypeFromTypeNode(typePredicateNode.type) - }; - } } else { // TypeScript 1.0 spec (April 2014): @@ -17410,7 +17834,7 @@ var ts; returnType = anyType; } } - links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -17423,7 +17847,7 @@ var ts; switch (node.kind) { case 152 /* FunctionType */: case 153 /* ConstructorType */: - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 144 /* Constructor */: @@ -17432,8 +17856,8 @@ var ts; case 149 /* IndexSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: // Don't include signature if node is the implementation of an overloaded function. A node is considered // an implementation node if it has a body and the previous node is of the same kind and immediately // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). @@ -17499,7 +17923,7 @@ var ts; return anyType; } function getSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } function getErasedSignature(signature) { if (!signature.typeParameters) @@ -17509,7 +17933,7 @@ var ts; signature.erasedSignatureCache = instantiateSignature(getErasedSignature(signature.target), signature.mapper); } else { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); } } return signature.erasedSignatureCache; @@ -17556,17 +17980,38 @@ var ts; ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType : undefined; } - function getConstraintOfTypeParameter(type) { - if (!type.constraint) { - if (type.target) { - var targetConstraint = getConstraintOfTypeParameter(type.target); - type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 137 /* TypeParameter */).constraint; + } + function hasConstraintReferenceTo(type, target) { + var checked; + while (type && type.flags & 512 /* TypeParameter */ && !ts.contains(checked, type)) { + if (type === target) { + return true; + } + (checked || (checked = [])).push(type); + var constraintDeclaration = getConstraintDeclaration(type); + type = constraintDeclaration && getTypeFromTypeNode(constraintDeclaration); + } + return false; + } + function getConstraintOfTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 137 /* TypeParameter */).constraint); + var constraintDeclaration = getConstraintDeclaration(typeParameter); + var constraint = getTypeFromTypeNode(constraintDeclaration); + if (hasConstraintReferenceTo(constraint, typeParameter)) { + error(constraintDeclaration, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + constraint = unknownType; + } + typeParameter.constraint = constraint; } } - return type.constraint === noConstraintType ? undefined : type.constraint; + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 137 /* TypeParameter */).parent); @@ -17614,50 +18059,6 @@ var ts; } return type; } - function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode, typeParameterSymbol) { - var links = getNodeLinks(typeReferenceNode); - if (links.isIllegalTypeReferenceInConstraint !== undefined) { - return links.isIllegalTypeReferenceInConstraint; - } - // bubble up to the declaration - var currentNode = typeReferenceNode; - // forEach === exists - while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { - currentNode = currentNode.parent; - } - // if last step was made from the type parameter this means that path has started somewhere in constraint which is illegal - links.isIllegalTypeReferenceInConstraint = currentNode.kind === 137 /* TypeParameter */; - return links.isIllegalTypeReferenceInConstraint; - } - function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { - var typeParameterSymbol; - function check(n) { - if (n.kind === 151 /* TypeReference */ && n.typeName.kind === 69 /* Identifier */) { - var links = getNodeLinks(n); - if (links.isIllegalTypeReferenceInConstraint === undefined) { - var symbol = resolveName(typeParameter, n.typeName.text, 793056 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - if (symbol && (symbol.flags & 262144 /* TypeParameter */)) { - // TypeScript 1.0 spec (April 2014): 3.4.1 - // Type parameters declared in a particular type parameter list - // may not be referenced in constraints in that type parameter list - // symbol.declaration.parent === typeParameter.parent - // -> typeParameter and symbol.declaration originate from the same type parameter list - // -> illegal for all declarations in symbol - // forEach === exists - links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent === typeParameter.parent; }); - } - } - if (links.isIllegalTypeReferenceInConstraint) { - error(typeParameter, ts.Diagnostics.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); - } - } - ts.forEachChild(n, check); - } - if (typeParameter.constraint) { - typeParameterSymbol = getSymbolOfNode(typeParameter); - check(typeParameter.constraint); - } - } // Get type from reference to class or interface function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(symbol); @@ -17702,13 +18103,6 @@ var ts; } // Get type from reference to named type that cannot be generic (enum or type parameter) function getTypeFromNonGenericTypeReference(node, symbol) { - if (symbol.flags & 262144 /* TypeParameter */ && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { - // TypeScript 1.0 spec (April 2014): 3.4.1 - // Type parameters declared in a particular type parameter list - // may not be referenced in constraints in that type parameter list - // Implementation: such type references are resolved to 'unknown' type that usually denotes error - return unknownType; - } if (node.typeArguments) { error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); return unknownType; @@ -17751,9 +18145,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: return declaration; } } @@ -17785,10 +18179,6 @@ var ts; if (arity === void 0) { arity = 0; } return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } - function tryGetGlobalType(name, arity) { - if (arity === void 0) { arity = 0; } - return getTypeOfGlobalSymbol(getGlobalSymbol(name, 793056 /* Type */, /*diagnostic*/ undefined), arity); - } /** * Returns a type that is inside a namespace at the global scope, e.g. * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type @@ -17908,7 +18298,7 @@ var ts; // a named type that circularly references itself. function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { - return emptyObjectType; + return emptyUnionType; } var typeSet = []; addTypesToSet(typeSet, types, 16384 /* Union */); @@ -17980,8 +18370,7 @@ var ts; } return links.resolvedType; } - function getStringLiteralType(node) { - var text = node.text; + function getStringLiteralTypeForText(text) { if (ts.hasProperty(stringLiteralTypes, text)) { return stringLiteralTypes[text]; } @@ -17989,17 +18378,17 @@ var ts; type.text = text; return type; } - function getTypeFromStringLiteral(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralType(node); + links.resolvedType = getStringLiteralTypeForText(node.text); } return links.resolvedType; } function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 215 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 217 /* InterfaceDeclaration */)) { if (!(container.flags & 64 /* Static */) && (container.kind !== 144 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -18015,6 +18404,22 @@ var ts; } return links.resolvedType; } + function getPredicateType(node) { + return createPredicateType(getSymbolOfNode(node), createTypePredicateFromTypePredicateNode(node)); + } + function createPredicateType(symbol, predicate) { + var type = createType(8 /* Boolean */ | 134217728 /* PredicateType */); + type.symbol = symbol; + type.predicate = predicate; + return type; + } + function getTypeFromPredicateTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getPredicateType(node); + } + return links.resolvedType; + } function getTypeFromTypeNode(node) { switch (node.kind) { case 117 /* AnyKeyword */: @@ -18029,15 +18434,15 @@ var ts; return esSymbolType; case 103 /* VoidKeyword */: return voidType; - case 97 /* ThisKeyword */: + case 161 /* ThisType */: return getTypeFromThisTypeNode(node); - case 9 /* StringLiteral */: - return getTypeFromStringLiteral(node); + case 162 /* StringLiteralType */: + return getTypeFromStringLiteralTypeNode(node); case 151 /* TypeReference */: return getTypeFromTypeReference(node); case 150 /* TypePredicate */: - return booleanType; - case 188 /* ExpressionWithTypeArguments */: + return getTypeFromPredicateTypeNode(node); + case 190 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); case 154 /* TypeQuery */: return getTypeFromTypeQueryNode(node); @@ -18117,18 +18522,22 @@ var ts; return t; }; } - function createInferenceMapper(context) { - var mapper = function (t) { - for (var i = 0; i < context.typeParameters.length; i++) { - if (t === context.typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); + function getInferenceMapper(context) { + if (!context.mapper) { + var mapper = function (t) { + var typeParameters = context.typeParameters; + for (var i = 0; i < typeParameters.length; i++) { + if (t === typeParameters[i]) { + context.inferences[i].isFixed = true; + return getInferredType(context, i); + } } - } - return t; - }; - mapper.context = context; - return mapper; + return t; + }; + mapper.context = context; + context.mapper = mapper; + } + return context.mapper; } function identityMapper(type) { return type; @@ -18136,33 +18545,42 @@ var ts; function combineTypeMappers(mapper1, mapper2) { return function (t) { return instantiateType(mapper1(t), mapper2); }; } - function instantiateTypeParameter(typeParameter, mapper) { + function cloneTypeParameter(typeParameter) { var result = createType(512 /* TypeParameter */); result.symbol = typeParameter.symbol; - if (typeParameter.constraint) { - result.constraint = instantiateType(typeParameter.constraint, mapper); + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; } else { - result.target = typeParameter; - result.mapper = mapper; + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; } - return result; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; - var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } } - if (signature.typePredicate) { - freshTypePredicate = { - parameterName: signature.typePredicate.parameterName, - parameterIndex: signature.typePredicate.parameterIndex, - type: instantiateType(signature.typePredicate.type, mapper) - }; - } - var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; return result; @@ -18226,6 +18644,10 @@ var ts; if (type.flags & 32768 /* Intersection */) { return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); } + if (type.flags & 134217728 /* PredicateType */) { + var predicate = type.predicate; + return createPredicateType(type.symbol, cloneTypePredicate(predicate, mapper)); + } } return type; } @@ -18234,25 +18656,25 @@ var ts; function isContextSensitive(node) { ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return isContextSensitiveFunctionLikeDeclaration(node); - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return node.operatorToken.kind === 52 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: return isContextSensitive(node.initializer); case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: return isContextSensitiveFunctionLikeDeclaration(node); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return isContextSensitive(node.expression); } return false; @@ -18278,7 +18700,7 @@ var ts; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); } - function compareTypes(source, target) { + function compareTypesIdentical(source, target) { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; } function isTypeSubtypeOf(source, target) { @@ -18293,10 +18715,84 @@ var ts; function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } - function isSignatureAssignableTo(source, target) { - var sourceType = getOrCreateTypeFromSignature(source); - var targetType = getOrCreateTypeFromSignature(target); - return checkTypeRelatedTo(sourceType, targetType, assignableRelation, /*errorNode*/ undefined); + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return true; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return false; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + for (var i = 0; i < checkCount; i++) { + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + var related = isTypeAssignableTo(t, s) || isTypeAssignableTo(s, t); + if (!related) { + return false; + } + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return true; + } + var sourceReturnType = getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + if (targetReturnType.flags & 134217728 /* PredicateType */ && targetReturnType.predicate.kind === 1 /* Identifier */) { + if (!(sourceReturnType.flags & 134217728 /* PredicateType */)) { + return false; + } + } + return isTypeAssignableTo(sourceReturnType, targetReturnType); + } + return true; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, /*errorNode*/ undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, /*errorNode*/ undefined)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + // If both have rest parameters, get the max and add 1 to + // compensate for the rest parameter. + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + // Return the count for whichever signature doesn't have rest parameters. + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). @@ -18370,6 +18866,11 @@ var ts; 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)) { + return result; + } + } if (source.flags & 256 /* StringLiteral */ && target === stringType) return -1 /* True */; if (relation === assignableRelation) { @@ -18378,6 +18879,36 @@ var ts; if (source === numberType && target.flags & 128 /* Enum */) return -1 /* True */; } + if (source.flags & 8 /* Boolean */ && target.flags & 8 /* Boolean */) { + if (source.flags & 134217728 /* PredicateType */ && target.flags & 134217728 /* PredicateType */) { + var sourcePredicate = source; + var targetPredicate = target; + if (sourcePredicate.predicate.kind !== targetPredicate.predicate.kind) { + if (reportErrors) { + reportError(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + if (sourcePredicate.predicate.kind === 1 /* Identifier */) { + var sourceIdentifierPredicate = sourcePredicate.predicate; + var targetIdentifierPredicate = targetPredicate.predicate; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + } + var related = isRelatedTo(sourcePredicate.predicate.type, targetPredicate.predicate.type, reportErrors, headMessage); + if (related === 0 /* False */ && reportErrors) { + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); + } + return related; + } + return -1 /* True */; + } if (source.flags & 1048576 /* FreshObjectLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -18471,9 +19002,6 @@ var ts; } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } - if (source.flags & 512 /* TypeParameter */ && target.flags & 512 /* TypeParameter */) { - return typeParameterIdenticalTo(source, target); - } if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target)) { @@ -18529,7 +19057,7 @@ var ts; var sourceTypes = source.types; for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { var sourceType = sourceTypes_1[_i]; - var related = typeRelatedToSomeType(sourceType, target, false); + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); if (!related) { return 0 /* False */; } @@ -18589,8 +19117,9 @@ var ts; if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } + var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1 /* True */; - for (var i = 0; i < targets.length; i++) { + for (var i = 0; i < length; i++) { var related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return 0 /* False */; @@ -18599,31 +19128,24 @@ var ts; } return result; } - function typeParameterIdenticalTo(source, target) { - // covers case when both type parameters does not have constraint (both equal to noConstraintType) - if (source.constraint === target.constraint) { - return -1 /* True */; - } - if (source.constraint === noConstraintType || target.constraint === noConstraintType) { - return 0 /* False */; - } - return isIdenticalTo(source.constraint, target.constraint); - } // Determine if two object types are related by structure. First, check if the result is already available in the global cache. // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function objectTypeRelatedTo(apparentSource, originalSource, target, reportErrors) { + function objectTypeRelatedTo(source, originalSource, target, reportErrors) { if (overflow) { return 0 /* False */; } - var id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { - // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate - // errors, we can use the cached value. Otherwise, recompute the relation - if (!elaborateErrors || (related === 3 /* FailedAndReported */)) { + if (elaborateErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported + // failure and continue computing the relation such that errors get reported. + relation[id] = 3 /* FailedAndReported */; + } + else { return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; } } @@ -18645,13 +19167,13 @@ var ts; maybeStack = []; expandingFlags = 0; } - sourceStack[depth] = apparentSource; + sourceStack[depth] = source; targetStack[depth] = target; maybeStack[depth] = {}; maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; @@ -18660,15 +19182,15 @@ var ts; result = 1 /* Maybe */; } else { - result = propertiesRelatedTo(apparentSource, target, reportErrors); + result = propertiesRelatedTo(source, target, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 0 /* Call */, reportErrors); + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 1 /* Construct */, reportErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportErrors); if (result) { - result &= stringIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= stringIndexTypesRelatedTo(source, originalSource, target, reportErrors); if (result) { - result &= numberIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= numberIndexTypesRelatedTo(source, originalSource, target, reportErrors); } } } @@ -18800,75 +19322,51 @@ var ts; } var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length && + isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignablity + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } var result = -1 /* True */; var saveErrorInfo = errorInfo; - if (kind === 1 /* Construct */) { - // Only want to compare the construct signatures for abstractness guarantees. - // Because the "abstractness" of a class is the same across all construct signatures - // (internally we are checking the corresponding declaration), it is enough to perform - // the check and report an error once over all pairs of source and target construct signatures. - // - // sourceSig and targetSig are (possibly) undefined. - // - // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. - var sourceSig = sourceSignatures[0]; - var targetSig = targetSignatures[0]; - result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); - if (result !== -1 /* True */) { - return result; - } - } outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; if (!t.hasStringLiterals || target.flags & 262144 /* FromSignature */) { - var localErrors = reportErrors; - var checkedAbstractAssignability = false; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { var s = sourceSignatures_1[_a]; if (!s.hasStringLiterals || source.flags & 262144 /* FromSignature */) { - var related = signatureRelatedTo(s, t, localErrors); + var related = signatureRelatedTo(s, t, shouldElaborateErrors); if (related) { result &= related; errorInfo = saveErrorInfo; continue outer; } - // Only report errors from the first failure - localErrors = false; + shouldElaborateErrors = false; } } + // don't elaborate the primitive apparent types (like Number) + // because the actual primitives will have already been reported. + if (shouldElaborateErrors && !isPrimitiveApparentType(source)) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } return 0 /* False */; } } return result; - function abstractSignatureRelatedTo(source, sourceSig, target, targetSig) { - if (sourceSig && targetSig) { - var sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); - var targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); - if (!sourceDecl) { - // If the source object isn't itself a class declaration, it can be freely assigned, regardless - // of whether the constructed object is abstract or not. - return -1 /* True */; - } - var sourceErasedSignature = getErasedSignature(sourceSig); - var targetErasedSignature = getErasedSignature(targetSig); - var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); - var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); - var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); - var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128 /* Abstract */; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128 /* Abstract */; - if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { - // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0 /* False */; - } - } - return -1 /* True */; - } } + /** + * See signatureAssignableTo, signatureAssignableTo + */ function signatureRelatedTo(source, target, reportErrors) { + // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; } @@ -18905,7 +19403,7 @@ var ts; var saveErrorInfo = errorInfo; var related = isRelatedTo(s, t, reportErrors); if (!related) { - related = isRelatedTo(t, s, false); + related = isRelatedTo(t, s, /*reportErrors*/ false); if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); @@ -18916,37 +19414,20 @@ var ts; } result &= related; } - if (source.typePredicate && target.typePredicate) { - var hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; - var hasDifferentTypes; - if (hasDifferentParameterIndex || - (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + if (targetReturnType.flags & 134217728 /* PredicateType */ && targetReturnType.predicate.kind === 1 /* Identifier */) { + if (!(sourceReturnType.flags & 134217728 /* PredicateType */)) { if (reportErrors) { - var sourceParamText = source.typePredicate.parameterName; - var targetParamText = target.typePredicate.parameterName; - var sourceTypeText = typeToString(source.typePredicate.type); - var targetTypeText = typeToString(target.typePredicate.type); - if (hasDifferentParameterIndex) { - reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceParamText, targetParamText); - } - else if (hasDifferentTypes) { - reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceTypeText, targetTypeText); - } - reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, sourceParamText + " is " + sourceTypeText, targetParamText + " is " + targetTypeText); + reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); } return 0 /* False */; } } - else if (!source.typePredicate && target.typePredicate) { - if (reportErrors) { - reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); - } - return 0 /* False */; - } - var targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) - return result; - var sourceReturnType = getReturnTypeOfSignature(source); return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); } function signaturesIdenticalTo(source, target, kind) { @@ -18956,8 +19437,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var i = 0, len = sourceSignatures.length; i < len; ++i) { - var related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + for (var i = 0, len = sourceSignatures.length; i < len; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); if (!related) { return 0 /* False */; } @@ -19016,7 +19497,7 @@ var ts; var related; if (sourceStringType && sourceNumberType) { // If we know for sure we're testing both string and numeric index types then only report errors from the second one - related = isRelatedTo(sourceStringType, targetType, false) || isRelatedTo(sourceNumberType, targetType, reportErrors); + related = isRelatedTo(sourceStringType, targetType, /*reportErrors*/ false) || isRelatedTo(sourceNumberType, targetType, reportErrors); } else { related = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors); @@ -19042,6 +19523,38 @@ var ts; } return 0 /* False */; } + function enumRelatedTo(source, target) { + 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 */)) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + return 0 /* False */; + } + } + } + return -1 /* True */; + } + } + // Return true if the given type is the constructor type for an abstract class + function isAbstractConstructorType(type) { + if (type.flags & 65536 /* Anonymous */) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && declaration.flags & 128 /* Abstract */) { + return true; + } + } + } + return false; } // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case // when structural type comparisons have been started for 10 or more instantiations of the same generic type. It is possible, @@ -19065,7 +19578,7 @@ var ts; return false; } function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypes) !== 0 /* False */; + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; } function compareProperties(sourceProp, targetProp, compareTypes) { // Two members are considered identical when @@ -19108,33 +19621,30 @@ var ts; } return false; } - function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; } if (!(isMatchingSignature(source, target, partialMatch))) { return 0 /* False */; } - var result = -1 /* True */; - if (source.typeParameters && target.typeParameters) { - if (source.typeParameters.length !== target.typeParameters.length) { - return 0 /* False */; - } - for (var i = 0, len = source.typeParameters.length; i < len; ++i) { - var related = compareTypes(source.typeParameters[i], target.typeParameters[i]); - if (!related) { - return 0 /* False */; - } - result &= related; - } - } - else if (source.typeParameters || target.typeParameters) { + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) { return 0 /* False */; } // Spec 1.0 Section 3.8.3 & 3.8.4: // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N source = getErasedSignature(source); target = getErasedSignature(target); + var result = -1 /* True */; var targetLen = target.parameters.length; for (var i = 0; i < targetLen; i++) { var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); @@ -19262,10 +19772,13 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); } function getWidenedType(type) { - if (type.flags & 6291456 /* RequiresWidening */) { + if (type.flags & 140509184 /* RequiresWidening */) { if (type.flags & (32 /* Undefined */ | 64 /* Null */)) { return anyType; } + if (type.flags & 134217728 /* PredicateType */) { + return booleanType; + } if (type.flags & 524288 /* ObjectLiteral */) { return getWidenedTypeOfObjectLiteral(type); } @@ -19340,13 +19853,13 @@ var ts; ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -19393,13 +19906,7 @@ var ts; } } function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var unused = typeParameters_1[_i]; - inferences.push({ - primary: undefined, secondary: undefined, isFixed: false - }); - } + var inferences = ts.map(typeParameters, createTypeInferencesObject); return { typeParameters: typeParameters, inferUnionTypes: inferUnionTypes, @@ -19407,6 +19914,13 @@ var ts; inferredTypes: new Array(typeParameters.length) }; } + function createTypeInferencesObject() { + return { + primary: undefined, + secondary: undefined, + isFixed: false + }; + } function inferTypes(context, source, target) { var sourceStack; var targetStack; @@ -19422,6 +19936,29 @@ var ts; return false; } function inferFromTypes(source, target) { + if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || + source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { + // Source and target are both unions or both intersections. First, find each + // target constituent type that has an identically matching source constituent + // type, and for each such target constituent type infer from the type to itself. + // When inferring from a type to itself we effectively find all type parameter + // occurrences within that type and infer themselves as their type arguments. + var matchingTypes; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (typeIdenticalToSomeType(t, source.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } if (target.flags & 512 /* 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). @@ -19463,6 +20000,11 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } + else if (source.flags & 134217728 /* PredicateType */ && target.flags & 134217728 /* PredicateType */) { + if (source.predicate.kind === target.predicate.kind) { + inferFromTypes(source.predicate.type, target.predicate.type); + } + } 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; @@ -19476,8 +20018,8 @@ var ts; var typeParameterCount = 0; var typeParameter; // First infer to each type in union or intersection that isn't a type parameter - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var t = targetTypes_2[_i]; + 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)) { typeParameter = t; typeParameterCount++; @@ -19499,16 +20041,18 @@ var ts; else if (source.flags & 49152 /* UnionOrIntersection */) { // Source is a union or intersection type, infer from each consituent type var sourceTypes = source.types; - for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { - var sourceType = sourceTypes_3[_a]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 /* ObjectType */ && (target.flags & (4096 /* Reference */ | 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, a tuple type, the type of a method, or a type literal, infer from members + 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 (isInProcess(source, target)) { return; } @@ -19554,17 +20098,7 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - if (source.typePredicate && target.typePredicate) { - if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { - // Return types from type predicates are treated as booleans. In order to infer types - // from type predicates we would need to infer using the type within the type predicate - // (i.e. 'Foo' from 'x is Foo'). - inferFromTypes(source.typePredicate.type, target.typePredicate.type); - } - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } function inferFromIndexTypes(source, target, sourceKind, targetKind) { var targetIndexType = getIndexTypeOfType(target, targetKind); @@ -19576,6 +20110,29 @@ var ts; } } } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 16384 /* Union */ ? getUnionType(reducedTypes, /*noSubtypeReduction*/ true) : getIntersectionType(reducedTypes); + } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; @@ -19599,10 +20156,16 @@ var ts; inferredType = emptyObjectType; inferenceSucceeded = true; } + context.inferredTypes[index] = inferredType; // Only do the constraint check if inference succeeded (to prevent cascading errors) if (inferenceSucceeded) { var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); - inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + context.inferredTypes[index] = inferredType = instantiatedConstraint; + } + } } else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { // If inference failed, it is necessary to record the index of the failed type parameter (the one we are on). @@ -19610,7 +20173,6 @@ var ts; // So if this failure is on preceding type parameter, this type parameter is the new failure index. context.failedTypeParameterIndex = index; } - context.inferredTypes[index] = inferredType; } return inferredType; } @@ -19620,9 +20182,6 @@ var ts; } return context.inferredTypes; } - function hasAncestor(node, kind) { - return ts.getAncestor(node, kind) !== undefined; - } // EXPRESSION TYPE CHECKING function getResolvedSymbol(node) { var links = getNodeLinks(node); @@ -19649,26 +20208,6 @@ var ts; } ts.Debug.fail("should not get here"); } - // For a union type, remove all constituent types that are of the given type kind (when isOfTypeKind is true) - // or not of the given type kind (when isOfTypeKind is false) - function removeTypesFromUnionType(type, typeKind, isOfTypeKind, allowEmptyUnionResult) { - if (type.flags & 16384 /* Union */) { - var types = type.types; - if (ts.forEach(types, function (t) { return !!(t.flags & typeKind) === isOfTypeKind; })) { - // Above we checked if we have anything to remove, now use the opposite test to do the removal - var narrowedType = getUnionType(ts.filter(types, function (t) { return !(t.flags & typeKind) === isOfTypeKind; })); - if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { - return narrowedType; - } - } - } - else if (allowEmptyUnionResult && !!(type.flags & typeKind) === isOfTypeKind) { - // Use getUnionType(emptyArray) instead of emptyObjectType in case the way empty union types - // are represented ever changes. - return getUnionType(emptyArray); - } - return type; - } function hasInitializer(node) { return !!(node.initializer || ts.isBindingPattern(node.parent) && hasInitializer(node.parent.parent)); } @@ -19687,10 +20226,7 @@ var ts; return links.assignmentChecks[symbol.id] = isAssignedIn(node); function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 56 /* FirstAssignment */ && node.operatorToken.kind <= 68 /* LastAssignment */) { - var n = node.left; - while (n.kind === 172 /* ParenthesizedExpression */) { - n = n.expression; - } + var n = skipParenthesizedNodes(node.left); if (n.kind === 69 /* Identifier */ && getResolvedSymbol(n) === symbol) { return true; } @@ -19705,55 +20241,55 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return isAssignedInBinaryExpression(node); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: return isAssignedInVariableDeclaration(node); - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: - case 172 /* ParenthesizedExpression */: - case 179 /* PrefixUnaryExpression */: - case 175 /* DeleteExpression */: - case 178 /* AwaitExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 180 /* PostfixUnaryExpression */: - case 184 /* YieldExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 192 /* Block */: - case 193 /* VariableStatement */: - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 204 /* ReturnStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - case 235 /* JsxOpeningElement */: - case 240 /* JsxExpression */: + case 163 /* ObjectBindingPattern */: + case 164 /* ArrayBindingPattern */: + case 166 /* ArrayLiteralExpression */: + case 167 /* ObjectLiteralExpression */: + case 168 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: + case 173 /* TypeAssertionExpression */: + case 191 /* AsExpression */: + case 174 /* ParenthesizedExpression */: + case 181 /* PrefixUnaryExpression */: + case 177 /* DeleteExpression */: + case 180 /* AwaitExpression */: + case 178 /* TypeOfExpression */: + case 179 /* VoidExpression */: + case 182 /* PostfixUnaryExpression */: + case 186 /* YieldExpression */: + case 184 /* ConditionalExpression */: + case 187 /* SpreadElementExpression */: + case 194 /* Block */: + case 195 /* VariableStatement */: + case 197 /* ExpressionStatement */: + case 198 /* IfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 206 /* ReturnStatement */: + case 207 /* WithStatement */: + case 208 /* SwitchStatement */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: + case 209 /* LabeledStatement */: + case 210 /* ThrowStatement */: + case 211 /* TryStatement */: + case 246 /* CatchClause */: + case 235 /* JsxElement */: + case 236 /* JsxSelfClosingElement */: + case 240 /* JsxAttribute */: + case 241 /* JsxSpreadAttribute */: + case 237 /* JsxOpeningElement */: + case 242 /* JsxExpression */: return ts.forEachChild(node, isAssignedIn); } return false; @@ -19765,59 +20301,73 @@ var ts; // Only narrow when symbol is variable of type any or an object, union, or type parameter type if (node && symbol.flags & 3 /* Variable */) { if (isTypeAny(type) || type.flags & (80896 /* ObjectType */ | 16384 /* Union */ | 512 /* TypeParameter */)) { + var declaration = ts.getDeclarationOfKind(symbol, 213 /* VariableDeclaration */); + var top_1 = declaration && getDeclarationContainer(declaration); + var originalType = type; + var nodeStack = []; loop: while (node.parent) { var child = node; node = node.parent; - var narrowedType = type; switch (node.kind) { - case 196 /* IfStatement */: - // In a branch of an if statement, narrow based on controlling expression - if (child !== node.expression) { - narrowedType = narrowType(type, node.expression, /*assumeTrue*/ child === node.thenStatement); - } + case 198 /* IfStatement */: + case 184 /* ConditionalExpression */: + case 183 /* BinaryExpression */: + nodeStack.push({ node: node, child: child }); break; - case 182 /* ConditionalExpression */: - // In a branch of a conditional expression, narrow based on controlling condition - if (child !== node.condition) { - narrowedType = narrowType(type, node.condition, /*assumeTrue*/ child === node.whenTrue); - } - break; - case 181 /* BinaryExpression */: - // In the right operand of an && or ||, narrow based on left operand - if (child === node.right) { - if (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { - narrowedType = narrowType(type, node.left, /*assumeTrue*/ true); - } - else if (node.operatorToken.kind === 52 /* BarBarToken */) { - narrowedType = narrowType(type, node.left, /*assumeTrue*/ false); - } - } - break; - case 248 /* SourceFile */: - case 218 /* ModuleDeclaration */: - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 144 /* Constructor */: - // Stop at the first containing function or module declaration + case 250 /* SourceFile */: + case 220 /* ModuleDeclaration */: + // Stop at the first containing file or module declaration break loop; } - // Use narrowed type if construct contains no assignments to variable - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; - } - type = narrowedType; + if (node === top_1) { + break; } } + var nodes; + while (nodes = nodeStack.pop()) { + var node_1 = nodes.node, child = nodes.child; + switch (node_1.kind) { + case 198 /* IfStatement */: + // In a branch of an if statement, narrow based on controlling expression + if (child !== node_1.expression) { + type = narrowType(type, node_1.expression, /*assumeTrue*/ child === node_1.thenStatement); + } + break; + case 184 /* ConditionalExpression */: + // In a branch of a conditional expression, narrow based on controlling condition + if (child !== node_1.condition) { + type = narrowType(type, node_1.condition, /*assumeTrue*/ child === node_1.whenTrue); + } + break; + case 183 /* BinaryExpression */: + // In the right operand of an && or ||, narrow based on left operand + if (child === node_1.right) { + if (node_1.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + type = narrowType(type, node_1.left, /*assumeTrue*/ true); + } + else if (node_1.operatorToken.kind === 52 /* BarBarToken */) { + type = narrowType(type, node_1.left, /*assumeTrue*/ false); + } + } + break; + default: + ts.Debug.fail("Unreachable!"); + } + // Use original type if construct contains assignments to variable + if (type !== originalType && isVariableAssignedWithin(symbol, node_1)) { + type = originalType; + } + } + // Preserve old top-level behavior - if the branch is really an empty set, revert to prior type + if (type === emptyUnionType) { + type = originalType; + } } } return type; function narrowTypeByEquality(type, expr, assumeTrue) { // Check that we have 'typeof ' on the left and string literal on the right - if (expr.left.kind !== 176 /* TypeOfExpression */ || expr.right.kind !== 9 /* StringLiteral */) { + if (expr.left.kind !== 178 /* TypeOfExpression */ || expr.right.kind !== 9 /* StringLiteral */) { return type; } var left = expr.left; @@ -19825,31 +20375,34 @@ var ts; if (left.expression.kind !== 69 /* Identifier */ || getResolvedSymbol(left.expression) !== symbol) { return type; } - var typeInfo = primitiveTypeInfo[right.text]; if (expr.operatorToken.kind === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue) { - // Assumed result is true. If check was not for a primitive type, remove all primitive types - if (!typeInfo) { - return removeTypesFromUnionType(type, /*typeKind*/ 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */ | 16777216 /* ESSymbol */, - /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); - } - // Check was for a primitive type, return that primitive type if it is a subtype - if (isTypeSubtypeOf(typeInfo.type, type)) { - return typeInfo.type; - } - // Otherwise, remove all types that aren't of the primitive type kind. This can happen when the type is - // union of enum types and other types. - return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ false, /*allowEmptyUnionResult*/ false); + var typeInfo = primitiveTypeInfo[right.text]; + // Don't narrow `undefined` + if (typeInfo && typeInfo.type === undefinedType) { + return type; + } + // If the type to be narrowed is any and we're checking a primitive with assumeTrue=true, return the primitive + if (!!(type.flags & 1 /* Any */) && typeInfo && assumeTrue) { + return typeInfo.type; + } + var flags; + if (typeInfo) { + flags = typeInfo.flags; } else { - // Assumed result is false. If check was for a primitive type, remove that primitive type - if (typeInfo) { - return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); - } - // Otherwise we don't have enough information to do anything. - return type; + assumeTrue = !assumeTrue; + flags = 132 /* NumberLike */ | 258 /* StringLike */ | 16777216 /* ESSymbol */ | 8 /* Boolean */; + } + // At this point we can bail if it's not a union + if (!(type.flags & 16384 /* Union */)) { + // If the active non-union type would be removed from a union by this type guard, return an empty union + return filterUnion(type) ? type : emptyUnionType; + } + return getUnionType(ts.filter(type.types, filterUnion), /*noSubtypeReduction*/ true); + function filterUnion(type) { + return assumeTrue === !!(type.flags & flags); } } function narrowTypeByAnd(type, expr, assumeTrue) { @@ -19862,7 +20415,7 @@ var ts; // and the second operand was false. We narrow with those assumptions and union the two resulting types. return getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ false), - narrowType(narrowType(type, expr.left, /*assumeTrue*/ true), expr.right, /*assumeTrue*/ false) + narrowType(type, expr.right, /*assumeTrue*/ false) ]); } } @@ -19872,7 +20425,7 @@ var ts; // and the second operand was true. We narrow with those assumptions and union the two resulting types. return getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ true), - narrowType(narrowType(type, expr.left, /*assumeTrue*/ false), expr.right, /*assumeTrue*/ true) + narrowType(type, expr.right, /*assumeTrue*/ true) ]); } else { @@ -19913,17 +20466,17 @@ var ts; } } if (targetType) { - if (!assumeTrue) { - if (type.flags & 16384 /* Union */) { - return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, targetType); })); - } - return type; - } - return getNarrowedType(type, targetType); + return getNarrowedType(type, targetType, assumeTrue); } return type; } - function getNarrowedType(originalType, narrowedTypeCandidate) { + function getNarrowedType(originalType, narrowedTypeCandidate, assumeTrue) { + if (!assumeTrue) { + if (originalType.flags & 16384 /* Union */) { + return getUnionType(ts.filter(originalType.types, function (t) { return !isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } // If the current type is a union type, remove all constituents that aren't assignable to target. If that produces // 0 candidates, fall back to the assignability check if (originalType.flags & 16384 /* Union */) { @@ -19943,28 +20496,62 @@ var ts; return type; } var signature = getResolvedSignature(expr); - if (signature.typePredicate && - expr.arguments[signature.typePredicate.parameterIndex] && - getSymbolAtLocation(expr.arguments[signature.typePredicate.parameterIndex]) === symbol) { - if (!assumeTrue) { - if (type.flags & 16384 /* Union */) { - return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, signature.typePredicate.type); })); - } - return type; + var predicateType = getReturnTypeOfSignature(signature); + if (!predicateType || !(predicateType.flags & 134217728 /* PredicateType */)) { + return type; + } + var predicate = predicateType.predicate; + if (ts.isIdentifierTypePredicate(predicate)) { + var callExpression = expr; + if (callExpression.arguments[predicate.parameterIndex] && + getSymbolAtTypePredicatePosition(callExpression.arguments[predicate.parameterIndex]) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); } - return getNarrowedType(type, signature.typePredicate.type); + } + else { + var expression = skipParenthesizedNodes(expr.expression); + return narrowTypeByThisTypePredicate(type, predicate, expression, assumeTrue); } return type; } + function narrowTypeByTypePredicateMember(type, expr, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + var memberType = getTypeOfExpression(expr); + if (!(memberType.flags & 134217728 /* PredicateType */)) { + return type; + } + return narrowTypeByThisTypePredicate(type, memberType.predicate, expr, assumeTrue); + } + function narrowTypeByThisTypePredicate(type, predicate, expression, assumeTrue) { + if (expression.kind === 169 /* ElementAccessExpression */ || expression.kind === 168 /* PropertyAccessExpression */) { + var accessExpression = expression; + var possibleIdentifier = skipParenthesizedNodes(accessExpression.expression); + if (possibleIdentifier.kind === 69 /* Identifier */ && getSymbolAtTypePredicatePosition(possibleIdentifier) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); + } + } + return type; + } + function getSymbolAtTypePredicatePosition(expr) { + expr = skipParenthesizedNodes(expr); + switch (expr.kind) { + case 69 /* Identifier */: + case 168 /* PropertyAccessExpression */: + case 135 /* QualifiedName */: + return getSymbolOfEntityNameOrPropertyAccessExpression(expr); + } + } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 168 /* CallExpression */: + case 170 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: var operator = expr.operatorToken.kind; if (operator === 32 /* EqualsEqualsEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -19979,15 +20566,24 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: if (expr.operator === 49 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } break; + case 169 /* ElementAccessExpression */: + case 168 /* PropertyAccessExpression */: + return narrowTypeByTypePredicateMember(type, expr, assumeTrue); } return type; } } + function skipParenthesizedNodes(expression) { + while (expression.kind === 174 /* ParenthesizedExpression */) { + expression = expression.expression; + } + return expression; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. @@ -19998,7 +20594,7 @@ var ts; // can explicitly bound arguments objects if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 174 /* ArrowFunction */) { + if (container.kind === 176 /* ArrowFunction */) { if (languageVersion < 2 /* ES6 */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } @@ -20029,7 +20625,7 @@ var ts; function checkBlockScopedBindingCapturedInLoop(node, symbol) { if (languageVersion >= 2 /* ES6 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 244 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 246 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -20045,12 +20641,12 @@ var ts; // nesting structure: // (variable declaration or binding element) -> variable declaration list -> container container = symbol.valueDeclaration; - while (container.kind !== 212 /* VariableDeclarationList */) { + while (container.kind !== 214 /* VariableDeclarationList */) { container = container.parent; } // get the parent of variable declaration list container = container.parent; - if (container.kind === 193 /* VariableStatement */) { + if (container.kind === 195 /* VariableStatement */) { // if parent is variable statement - get its parent container = container.parent; } @@ -20085,17 +20681,17 @@ var ts; var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 174 /* ArrowFunction */) { + if (container.kind === 176 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code needToCaptureLexicalThis = (languageVersion < 2 /* ES6 */); } switch (container.kind) { - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; @@ -20121,6 +20717,21 @@ var ts; var symbol = getSymbolOfNode(container.parent); return container.flags & 64 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; } + // If this is a function in a JS file, it might be a class method. Check if it's the RHS + // of a x.prototype.y = function [name]() { .... } + if (ts.isInJavaScriptFile(node) && container.kind === 175 /* FunctionExpression */) { + if (ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') + var className = container.parent // x.protoype.y = f + .left // x.prototype.y + .expression // x.prototype + .expression; // x + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + return getInferredClassType(classSymbol); + } + } + } return anyType; } function isInConstructorArgumentInitializer(node, constructorDecl) { @@ -20132,55 +20743,75 @@ var ts; return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 168 /* CallExpression */ && node.parent.expression === node; - var classDeclaration = ts.getContainingClass(node); - var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - var container = ts.getSuperContainer(node, /*includeFunctions*/ true); + var isCallExpression = node.parent.kind === 170 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; if (!isCallExpression) { // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting - while (container && container.kind === 174 /* ArrowFunction */) { - container = ts.getSuperContainer(container, /*includeFunctions*/ true); + while (container && container.kind === 176 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; } } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; - // always set NodeCheckFlags for 'super' expression node - if (canUseSuperExpression) { - if ((container.flags & 64 /* Static */) || isCallExpression) { - nodeCheckFlag = 512 /* SuperStatic */; - } - else { - nodeCheckFlag = 256 /* SuperInstance */; - } - getNodeLinks(node).flags |= nodeCheckFlag; - if (needToCaptureLexicalThis) { - // call expressions are allowed only in constructors so they should always capture correct 'this' - // super property access expressions can also appear in arrow functions - - // in this case they should also use correct lexical this - captureLexicalThis(node.parent, container); - } - } - if (!baseClassType) { - if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } if (!canUseSuperExpression) { - if (container && container.kind === 136 /* ComputedPropertyName */) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = node; + while (current && current !== container && current.kind !== 136 /* ComputedPropertyName */) { + current = current.parent; + } + if (current && current.kind === 136 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 167 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } else { error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); } return unknownType; } + if ((container.flags & 64 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 167 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES6 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } if (container.kind === 144 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); @@ -20203,8 +20834,8 @@ var ts; // 'super' property access is allowed // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor - // topmost container must be something that is directly nested in the class declaration - if (container && ts.isClassLike(container.parent)) { + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 167 /* ObjectLiteralExpression */) { if (container.flags & 64 /* Static */) { return container.kind === 143 /* MethodDeclaration */ || container.kind === 142 /* MethodSignature */ || @@ -20327,7 +20958,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 170 /* TaggedTemplateExpression */) { + if (template.parent.kind === 172 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -20350,6 +20981,11 @@ var ts; } return type; } + else if (operator === 51 /* AmpersandAmpersandToken */ || operator === 24 /* CommaToken */) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } return undefined; } // Apply a mapping function to a contextual type and return the resulting type. If the contextual type @@ -20362,8 +20998,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var current = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -20449,22 +21085,20 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForJsxExpression(expr) { - // Contextual type only applies to JSX expressions that are in attribute assignments (not in 'Children' positions) - if (expr.parent.kind === 238 /* JsxAttribute */) { - var attrib = expr.parent; - var attrsType = getJsxElementAttributesType(attrib.parent); + function getContextualTypeForJsxAttribute(attribute) { + var kind = attribute.kind; + var jsxElement = attribute.parent; + var attrsType = getJsxElementAttributesType(jsxElement); + if (attribute.kind === 240 /* JsxAttribute */) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } - else { - return getTypeOfPropertyOfType(attrsType, attrib.name.text); - } + return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - if (expr.kind === 239 /* JsxSpreadAttribute */) { - return getJsxElementAttributesType(expr.parent); + else if (attribute.kind === 241 /* JsxSpreadAttribute */) { + return attrsType; } - return undefined; + ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -20499,39 +21133,41 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: case 138 /* Parameter */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 163 /* BindingElement */: + case 165 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 174 /* ArrowFunction */: - case 204 /* ReturnStatement */: + case 176 /* ArrowFunction */: + case 206 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 184 /* YieldExpression */: + case 186 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 173 /* TypeAssertionExpression */: + case 191 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 190 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 183 /* TemplateExpression */); + case 192 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 185 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return getContextualType(parent); - case 240 /* JsxExpression */: - case 239 /* JsxSpreadAttribute */: - return getContextualTypeForJsxExpression(parent); + case 242 /* JsxExpression */: + return getContextualType(parent); + case 240 /* JsxAttribute */: + case 241 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); } return undefined; } @@ -20547,7 +21183,7 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 173 /* FunctionExpression */ || node.kind === 174 /* ArrowFunction */; + return node.kind === 175 /* FunctionExpression */ || node.kind === 176 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -20573,15 +21209,15 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { // This signature will contribute to contextual union signature signatureList = [signature]; } - else if (!compareSignatures(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypes)) { + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { // Signatures aren't identical, do not use return undefined; } @@ -20624,13 +21260,13 @@ var ts; // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. function isAssignmentTarget(node) { var parent = node.parent; - if (parent.kind === 181 /* BinaryExpression */ && parent.operatorToken.kind === 56 /* EqualsToken */ && parent.left === node) { + if (parent.kind === 183 /* BinaryExpression */ && parent.operatorToken.kind === 56 /* EqualsToken */ && parent.left === node) { return true; } - if (parent.kind === 245 /* PropertyAssignment */) { + if (parent.kind === 247 /* PropertyAssignment */) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 164 /* ArrayLiteralExpression */) { + if (parent.kind === 166 /* ArrayLiteralExpression */) { return isAssignmentTarget(parent); } return false; @@ -20646,8 +21282,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); } function hasDefaultValue(node) { - return (node.kind === 163 /* BindingElement */ && !!node.initializer) || - (node.kind === 181 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */); + return (node.kind === 165 /* BindingElement */ && !!node.initializer) || + (node.kind === 183 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -20656,7 +21292,7 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 185 /* SpreadElementExpression */) { + if (inDestructuringPattern && e.kind === 187 /* SpreadElementExpression */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -20680,7 +21316,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 185 /* SpreadElementExpression */; + hasSpreadElement = hasSpreadElement || e.kind === 187 /* SpreadElementExpression */; } if (!hasSpreadElement) { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such @@ -20695,7 +21331,7 @@ var ts; var pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 162 /* ArrayBindingPattern */ || pattern.kind === 164 /* ArrayLiteralExpression */)) { + if (pattern && (pattern.kind === 164 /* ArrayBindingPattern */ || pattern.kind === 166 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -20703,7 +21339,7 @@ var ts; elementTypes.push(contextualType.elementTypes[i]); } else { - if (patternElement.kind !== 187 /* OmittedExpression */) { + if (patternElement.kind !== 189 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -20775,24 +21411,24 @@ var ts; var propertiesArray = []; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 161 /* ObjectBindingPattern */ || contextualType.pattern.kind === 165 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 163 /* ObjectBindingPattern */ || contextualType.pattern.kind === 167 /* ObjectLiteralExpression */); var typeFlags = 0; var patternWithComputedProperties = false; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 245 /* PropertyAssignment */ || - memberDecl.kind === 246 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 247 /* PropertyAssignment */ || + memberDecl.kind === 248 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 245 /* PropertyAssignment */) { + if (memberDecl.kind === 247 /* PropertyAssignment */) { type = checkPropertyAssignment(memberDecl, contextualMapper); } else if (memberDecl.kind === 143 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 246 /* ShorthandPropertyAssignment */); + ts.Debug.assert(memberDecl.kind === 248 /* ShorthandPropertyAssignment */); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; @@ -20800,8 +21436,8 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 245 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 246 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 247 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 248 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912 /* Optional */; } @@ -20893,38 +21529,22 @@ var ts; checkJsxOpeningLikeElement(node); return jsxElementType || anyType; } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 69 /* Identifier */) { - return lhs.text === rhs.text; - } - return lhs.right.text === rhs.right.text && - tagNamesAreEquivalent(lhs.left, rhs.left); - } function checkJsxElement(node) { // Check attributes checkJsxOpeningLikeElement(node.openingElement); - // Check that the closing tag matches - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - error(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNode(node.openingElement.tagName)); - } - else { - // Perform resolution on the closing tag so that rename/go to definition/etc work - getJsxElementTagSymbol(node.closingElement); - } + // Perform resolution on the closing tag so that rename/go to definition/etc work + getJsxElementTagSymbol(node.closingElement); // Check children for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 240 /* JsxExpression */: + case 242 /* JsxExpression */: checkJsxExpression(child); break; - case 233 /* JsxElement */: + case 235 /* JsxElement */: checkJsxElement(child); break; - case 234 /* JsxSelfClosingElement */: + case 236 /* JsxSelfClosingElement */: checkJsxSelfClosingElement(child); break; } @@ -21006,12 +21626,11 @@ var ts; } return type; } - /// Returns the type JSX.IntrinsicElements. May return `unknownType` if that type is not present. - function getJsxIntrinsicElementsType() { - if (!jsxIntrinsicElementsType) { - jsxIntrinsicElementsType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.IntrinsicElements) || unknownType; + function getJsxType(name) { + if (jsxTypes[name] === undefined) { + return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType; } - return jsxIntrinsicElementsType; + return jsxTypes[name]; } /// Given a JSX opening element or self-closing element, return the symbol of the property that the tag name points to if /// this is an intrinsic tag. This might be a named @@ -21020,7 +21639,6 @@ var ts; /// type or factory function. /// Otherwise, returns unknownSymbol. function getJsxElementTagSymbol(node) { - var flags = 8 /* UnknownElement */; var links = getNodeLinks(node); if (!links.resolvedSymbol) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -21032,7 +21650,7 @@ var ts; } return links.resolvedSymbol; function lookupIntrinsicTag(node) { - var intrinsicElementsType = getJsxIntrinsicElementsType(); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { // Property case var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); @@ -21060,7 +21678,7 @@ var ts; var valueSymbol = resolveJsxTagName(node); // Look up the value in the current scope if (valueSymbol && valueSymbol !== unknownSymbol) { - links.jsxFlags |= 4 /* ClassElement */; + links.jsxFlags |= 4 /* ValueElement */; if (valueSymbol.flags & 8388608 /* Alias */) { markAliasSymbolAsReferenced(valueSymbol); } @@ -21086,7 +21704,7 @@ var ts; function getJsxElementInstanceType(node) { // There is no such thing as an instance type for a non-class element. This // line shouldn't be hit. - ts.Debug.assert(!!(getNodeLinks(node).jsxFlags & 4 /* ClassElement */), "Should not call getJsxElementInstanceType on non-class Element"); + ts.Debug.assert(!!(getNodeLinks(node).jsxFlags & 4 /* ValueElement */), "Should not call getJsxElementInstanceType on non-class Element"); var classSymbol = getJsxElementTagSymbol(node); if (classSymbol === unknownSymbol) { // Couldn't find the class instance type. Error has already been issued @@ -21108,13 +21726,7 @@ var ts; return unknownType; } } - var returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); - // Issue an error if this return type isn't assignable to JSX.ElementClass - var elemClassType = getJsxGlobalElementClassType(); - if (elemClassType) { - checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - return returnType; + return getUnionType(signatures.map(getReturnTypeOfSignature)); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesPropery doesn't exist (which means all @@ -21156,8 +21768,27 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedJsxType) { var sym = getJsxElementTagSymbol(node); - if (links.jsxFlags & 4 /* ClassElement */) { + if (links.jsxFlags & 4 /* ValueElement */) { + // Get the element instance type (the result of newing or invoking this tag) var elemInstanceType = getJsxElementInstanceType(node); + // Is this is a stateless function component? See if its single signature is + // assignable to the JSX Element Type + var callSignature = getSingleCallSignature(getTypeOfSymbol(sym)); + var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); + var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType) && (paramType.flags & 80896 /* ObjectType */)) { + // Intersect in JSX.IntrinsicAttributes if it exists + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return paramType; + } + // Issue an error if this return type isn't assignable to JSX.ElementClass + var elemClassType = getJsxGlobalElementClassType(); + if (elemClassType) { + checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } @@ -21177,14 +21808,34 @@ var ts; return links.resolvedJsxType = emptyObjectType; } else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + // Props is of type 'any' or unknown return links.resolvedJsxType = attributesType; } - else if (!(attributesType.flags & 80896 /* ObjectType */)) { - error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_must_be_an_object_type, typeToString(attributesType)); + else if (attributesType.flags & 16384 /* 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 links.resolvedJsxType = anyType; } else { - return links.resolvedJsxType = attributesType; + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return links.resolvedJsxType = apparentAttributesType; } } } @@ -21219,7 +21870,7 @@ var ts; } /// Returns all the properties of the Jsx.IntrinsicElements interface function getJsxIntrinsicTagNames() { - var intrinsics = getJsxIntrinsicElementsType(); + var intrinsics = getJsxType(JsxNames.IntrinsicElements); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } function checkJsxPreconditions(errorNode) { @@ -21236,14 +21887,13 @@ var ts; function checkJsxOpeningLikeElement(node) { checkGrammarJsxElement(node); checkJsxPreconditions(node); - // If we're compiling under --jsx react, the symbol 'React' should - // be marked as 'used' so we don't incorrectly elide its import. And if there - // is no 'React' symbol in scope, we should issue an error. - if (compilerOptions.jsx === 2 /* React */) { - var reactSym = resolveName(node.tagName, "React", 107455 /* Value */, ts.Diagnostics.Cannot_find_name_0, "React"); - if (reactSym) { - getSymbolLinks(reactSym).referenced = true; - } + // The reactNamespace symbol should be marked as 'used' so we don't incorrectly elide its import. And if there + // is no reactNamespace symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); + if (reactSym) { + getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = {}; @@ -21252,11 +21902,11 @@ var ts; // thus should have their types ignored var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 238 /* JsxAttribute */) { + if (node.attributes[i].kind === 240 /* JsxAttribute */) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 239 /* JsxSpreadAttribute */); + ts.Debug.assert(node.attributes[i].kind === 241 /* JsxSpreadAttribute */); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -21303,7 +21953,7 @@ var ts; var flags = getDeclarationFlagsFromSymbol(prop); var declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (left.kind === 95 /* SuperKeyword */) { - var errorNode = node.kind === 166 /* PropertyAccessExpression */ ? + var errorNode = node.kind === 168 /* PropertyAccessExpression */ ? node.name : node.right; // TS 1.0 spec (April 2014): 4.8.2 @@ -21313,7 +21963,7 @@ var ts; // - In a static member function or static member accessor // where this references the constructor function object of a derived class, // a super property access is permitted and must specify a public static member function of the base class. - if (getDeclarationKindFromSymbol(prop) !== 143 /* MethodDeclaration */) { + if (languageVersion < 2 /* ES6 */ && getDeclarationKindFromSymbol(prop) !== 143 /* MethodDeclaration */) { // `prop` refers to a *property* declared in the super class // rather than a *method*, so it does not satisfy the above criteria. error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); @@ -21400,7 +22050,7 @@ var ts; return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 166 /* PropertyAccessExpression */ + var left = node.kind === 168 /* PropertyAccessExpression */ ? node.expression : node.left; var type = checkExpression(left); @@ -21416,7 +22066,7 @@ var ts; // Grammar checking if (!node.argumentExpression) { var sourceFile = getSourceFile(node); - if (node.parent.kind === 169 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 171 /* NewExpression */ && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -21497,7 +22147,7 @@ var ts; if (indexArgumentExpression.kind === 9 /* StringLiteral */ || indexArgumentExpression.kind === 8 /* NumericLiteral */) { return indexArgumentExpression.text; } - if (indexArgumentExpression.kind === 167 /* ElementAccessExpression */ || indexArgumentExpression.kind === 166 /* PropertyAccessExpression */) { + if (indexArgumentExpression.kind === 169 /* ElementAccessExpression */ || indexArgumentExpression.kind === 168 /* PropertyAccessExpression */) { var value = getConstantValue(indexArgumentExpression); if (value !== undefined) { return value.toString(); @@ -21552,7 +22202,7 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 172 /* TaggedTemplateExpression */) { checkExpression(node.template); } else if (node.kind !== 139 /* Decorator */) { @@ -21621,7 +22271,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 185 /* SpreadElementExpression */) { + if (arg && arg.kind === 187 /* SpreadElementExpression */) { return i; } } @@ -21633,13 +22283,13 @@ var ts; var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments var isDecorator; var spreadArgIndex = -1; - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 172 /* TaggedTemplateExpression */) { var tagExpression = node; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length adjustedArgCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 183 /* TemplateExpression */) { + if (tagExpression.template.kind === 185 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var templateExpression = tagExpression.template; @@ -21665,7 +22315,7 @@ var ts; var callExpression = node; if (!callExpression.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(callExpression.kind === 169 /* NewExpression */); + ts.Debug.assert(callExpression.kind === 171 /* NewExpression */); return signature.minArgumentCount === 0; } // For IDE scenarios we may have an incomplete call, so a trailing comma is tantamount to adding another argument. @@ -21717,7 +22367,7 @@ var ts; } function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; - var inferenceMapper = createInferenceMapper(context); + var inferenceMapper = getInferenceMapper(context); // Clear out all the inference results from the last time inferTypeArguments was called on this context for (var i = 0; i < typeParameters.length; i++) { // As an optimization, we don't have to clear (and later recompute) inferred types @@ -21744,7 +22394,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 187 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 189 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); // If the effective argument type is 'undefined', there is no synthetic type @@ -21775,14 +22425,11 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; + var mapper; for (var i = 0; i < typeParameters.length; i++) { - var typeArgNode = typeArguments[i]; - var typeArgument = getTypeFromTypeNode(typeArgNode); - // Do not push on this array! It has a preallocated length - typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable /* so far */) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { @@ -21792,7 +22439,11 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); typeArgumentHeadMessage = headMessage; } - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); } } } @@ -21803,7 +22454,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 187 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 189 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); @@ -21811,7 +22462,7 @@ var ts; // for the argument. In that case, we should check the argument. if (argType === undefined) { argType = arg.kind === 9 /* StringLiteral */ && !reportErrors - ? getStringLiteralType(arg) + ? getStringLiteralTypeForText(arg.text) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } // Use argument expression as error location when reporting errors @@ -21835,10 +22486,10 @@ var ts; */ function getEffectiveCallArguments(node) { var args; - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 172 /* TaggedTemplateExpression */) { var template = node.template; args = [undefined]; - if (template.kind === 183 /* TemplateExpression */) { + if (template.kind === 185 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); @@ -21871,8 +22522,8 @@ var ts; function getEffectiveArgumentCount(node, args, signature) { if (node.kind === 139 /* Decorator */) { switch (node.parent.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; case 141 /* PropertyDeclaration */: @@ -21915,7 +22566,7 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); @@ -21960,7 +22611,7 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } @@ -21984,7 +22635,7 @@ var ts; case 69 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getStringLiteralType(element.name); + return getStringLiteralTypeForText(element.name.text); case 136 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); if (allConstituentTypesHaveKind(nameType, 16777216 /* ESSymbol */)) { @@ -22011,7 +22662,7 @@ var ts; function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator // or its `parameterIndex` for a paramter decorator - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } @@ -22060,7 +22711,7 @@ var ts; if (node.kind === 139 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 172 /* TaggedTemplateExpression */) { return globalTemplateStringsArrayType; } // This is not a synthetic argument, so we return 'undefined' @@ -22073,7 +22724,7 @@ var ts; function getEffectiveArgument(node, args, argIndex) { // For a decorator or the first argument of a tagged template expression we return undefined. if (node.kind === 139 /* Decorator */ || - (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */)) { + (argIndex === 0 && node.kind === 172 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -22086,7 +22737,7 @@ var ts; // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 172 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -22095,7 +22746,7 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 170 /* TaggedTemplateExpression */; + var isTaggedTemplate = node.kind === 172 /* TaggedTemplateExpression */; var isDecorator = node.kind === 139 /* Decorator */; var typeArguments; if (!isTaggedTemplate && !isDecorator) { @@ -22202,7 +22853,8 @@ var ts; } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], /*reportErrors*/ true, headMessage); + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -22260,7 +22912,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -22441,8 +23093,8 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; case 138 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; @@ -22487,13 +23139,13 @@ var ts; // to correctly fill the candidatesOutArray. if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 168 /* CallExpression */) { + if (node.kind === 170 /* CallExpression */) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 169 /* NewExpression */) { + else if (node.kind === 171 /* NewExpression */) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 172 /* TaggedTemplateExpression */) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } else if (node.kind === 139 /* Decorator */) { @@ -22505,6 +23157,13 @@ var ts; } return links.resolvedSignature; } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } /** * Syntactically and semantically checks a call or new expression. * @param node The call/new expression to be checked. @@ -22517,14 +23176,20 @@ var ts; if (node.expression.kind === 95 /* SuperKeyword */) { return voidType; } - if (node.kind === 169 /* NewExpression */) { + if (node.kind === 171 /* NewExpression */) { var declaration = signature.declaration; if (declaration && declaration.kind !== 144 /* Constructor */ && declaration.kind !== 148 /* ConstructSignature */ && declaration.kind !== 153 /* ConstructorType */) { - // When resolved signature is a call signature (and not a construct signature) the result type is any - if (compilerOptions.noImplicitAny) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + var funcSymbol = checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */)) { + return getInferredClassType(funcSymbol); + } + else if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; @@ -22577,7 +23242,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 189 /* OmittedExpression */) { if (element.name.kind === 69 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -22642,7 +23307,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 192 /* Block */) { + if (func.body.kind !== 194 /* Block */) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -22755,38 +23420,53 @@ var ts; }); return aggregatedTypes; } - // TypeScript Specification 1.0 (6.3) - July 2014 - // An explicitly typed function whose return type isn't the Void or the Any type - // must have at least one return statement somewhere in its body. - // An exception to this rule is if the function implementation consists of a single 'throw' statement. + /* + *TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void or the Any type + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; } - // Functions that return 'void' or 'any' don't need any return expressions. + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. if (returnType === voidType || isTypeAny(returnType)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - // also if HasImplicitReturnValue flags is not set this means that all codepaths in function body end with return of throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 /* Block */ || !(func.flags & 524288 /* HasImplicitReturn */)) { + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (ts.nodeIsMissing(func.body) || func.body.kind !== 194 /* Block */ || !(func.flags & 524288 /* HasImplicitReturn */)) { return; } - if (func.flags & 1048576 /* HasExplicitReturn */) { - if (compilerOptions.noImplicitReturns) { - error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { - // This function does not conform to the specification. + var hasExplicitReturn = func.flags & 1048576 /* HasExplicitReturn */; + if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + var inferredReturnType = hasExplicitReturn + ? getReturnTypeOfSignature(getSignatureFromDeclaration(func)) + : voidType; + if (inferredReturnType === voidType || isTypeAny(inferredReturnType)) { + return; + } + } + error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 173 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 175 /* FunctionExpression */) { checkGrammarForGenerator(node); } // The identityMapper object is used to indicate that function expressions are wildcards @@ -22826,6 +23506,7 @@ var ts; } if (!contextChecked) { checkSignatureDeclaration(node); + checkNodeDeferred(node); } } } @@ -22835,19 +23516,16 @@ var ts; } return type; } - function checkFunctionExpressionOrObjectLiteralMethodBody(node) { + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; } - var returnType = node.type && getTypeFromTypeNode(node.type); - var promisedType; - if (returnType && isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - if (returnType && !node.asteriskToken) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + if (!node.asteriskToken) { + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { if (!node.type) { @@ -22858,7 +23536,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 192 /* Block */) { + if (node.body.kind === 194 /* Block */) { checkSourceElement(node.body); } else { @@ -22868,16 +23546,15 @@ var ts; // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. var exprType = checkExpression(node.body); - if (returnType) { + if (returnOrPromisedType) { if (isAsync) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); - checkTypeAssignableTo(awaitedType, promisedType, node.body); + checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } else { - checkTypeAssignableTo(exprType, returnType, node.body); + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } - checkFunctionAndClassExpressionBodies(node.body); } } } @@ -22911,17 +23588,17 @@ var ts; // An identifier expression that references any other kind of entity is classified as a value(and therefore cannot be the target of an assignment). return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 3 /* Variable */) !== 0; } - case 166 /* PropertyAccessExpression */: { + case 168 /* PropertyAccessExpression */: { var symbol = findSymbol(n); // TypeScript 1.0 spec (April 2014): 4.10 // A property access expression is always classified as a reference. // NOTE (not in spec): assignment to enum members should not be allowed return !symbol || symbol === unknownSymbol || (symbol.flags & ~8 /* EnumMember */) !== 0; } - case 167 /* ElementAccessExpression */: + case 169 /* ElementAccessExpression */: // old compiler doesn't check indexed access return true; - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return isReferenceOrErrorExpression(n.expression); default: return false; @@ -22930,11 +23607,11 @@ var ts; function isConstVariableReference(n) { switch (n.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: { + case 168 /* PropertyAccessExpression */: { var symbol = findSymbol(n); return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384 /* Const */) !== 0; } - case 167 /* ElementAccessExpression */: { + case 169 /* ElementAccessExpression */: { var index = n.argumentExpression; var symbol = findSymbol(n.expression); if (symbol && index && index.kind === 9 /* StringLiteral */) { @@ -22944,7 +23621,7 @@ var ts; } return false; } - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return isConstVariableReference(n.expression); default: return false; @@ -23025,8 +23702,8 @@ var ts; } if (type.flags & 49152 /* UnionOrIntersection */) { 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_10 = types; _i < types_10.length; _i++) { + var current = types_10[_i]; if (current.flags & kind) { return true; } @@ -23042,8 +23719,8 @@ var ts; } if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var current = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var current = types_11[_i]; if (!(current.flags & kind)) { return false; } @@ -23090,7 +23767,7 @@ var ts; var properties = node.properties; for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var p = properties_3[_i]; - if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { + if (p.kind === 247 /* PropertyAssignment */ || p.kind === 248 /* ShorthandPropertyAssignment */) { var name_13 = p.name; if (name_13.kind === 136 /* ComputedPropertyName */) { checkComputedPropertyName(name_13); @@ -23105,11 +23782,11 @@ var ts; isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1 /* Number */) || getIndexTypeOfType(sourceType, 0 /* String */); if (type) { - if (p.kind === 246 /* ShorthandPropertyAssignment */) { + if (p.kind === 248 /* ShorthandPropertyAssignment */) { checkDestructuringAssignment(p, type); } else { - // non-shorthand property assignments should always have initializers + // non-shorthand property assignments should always have initializers checkDestructuringAssignment(p.initializer, type); } } @@ -23131,8 +23808,8 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187 /* OmittedExpression */) { - if (e.kind !== 185 /* SpreadElementExpression */) { + if (e.kind !== 189 /* OmittedExpression */) { + if (e.kind !== 187 /* SpreadElementExpression */) { var propName = "" + i; var type = isTypeAny(sourceType) ? sourceType @@ -23157,7 +23834,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 181 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { + if (restExpression.kind === 183 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -23171,7 +23848,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 246 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 248 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -23181,14 +23858,14 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + if (target.kind === 183 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 165 /* ObjectLiteralExpression */) { + if (target.kind === 167 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 164 /* ArrayLiteralExpression */) { + if (target.kind === 166 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); @@ -23205,7 +23882,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 /* EqualsToken */ && (left.kind === 165 /* ObjectLiteralExpression */ || left.kind === 164 /* ArrayLiteralExpression */)) { + if (operator === 56 /* EqualsToken */ && (left.kind === 167 /* ObjectLiteralExpression */ || left.kind === 166 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); @@ -23441,7 +24118,7 @@ var ts; function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { - return getStringLiteralType(node); + return getStringLiteralTypeForText(node.text); } return stringType; } @@ -23527,8 +24204,8 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 167 /* ElementAccessExpression */ && node.parent.expression === node) || + var ok = (node.parent.kind === 168 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 169 /* ElementAccessExpression */ && node.parent.expression === node) || ((node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); @@ -23556,7 +24233,7 @@ var ts; return booleanType; case 8 /* NumericLiteral */: return checkNumericLiteral(node); - case 183 /* TemplateExpression */: + case 185 /* TemplateExpression */: return checkTemplateExpression(node); case 9 /* StringLiteral */: return checkStringLiteralExpression(node); @@ -23564,58 +24241,58 @@ var ts; return stringType; case 10 /* RegularExpressionLiteral */: return globalRegExpType; - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return checkArrayLiteral(node, contextualMapper); - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return checkObjectLiteral(node, contextualMapper); - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 167 /* ElementAccessExpression */: + case 169 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: return checkCallExpression(node); - case 170 /* TaggedTemplateExpression */: + case 172 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return checkExpression(node.expression, contextualMapper); - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: return checkClassExpression(node); - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 176 /* TypeOfExpression */: + case 178 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 173 /* TypeAssertionExpression */: + case 191 /* AsExpression */: return checkAssertion(node); - case 175 /* DeleteExpression */: + case 177 /* DeleteExpression */: return checkDeleteExpression(node); - case 177 /* VoidExpression */: + case 179 /* VoidExpression */: return checkVoidExpression(node); - case 178 /* AwaitExpression */: + case 180 /* AwaitExpression */: return checkAwaitExpression(node); - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 180 /* PostfixUnaryExpression */: + case 182 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return checkBinaryExpression(node, contextualMapper); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return checkConditionalExpression(node, contextualMapper); - case 185 /* SpreadElementExpression */: + case 187 /* SpreadElementExpression */: return checkSpreadElementExpression(node, contextualMapper); - case 187 /* OmittedExpression */: + case 189 /* OmittedExpression */: return undefinedType; - case 184 /* YieldExpression */: + case 186 /* YieldExpression */: return checkYieldExpression(node); - case 240 /* JsxExpression */: + case 242 /* JsxExpression */: return checkJsxExpression(node); - case 233 /* JsxElement */: + case 235 /* JsxElement */: return checkJsxElement(node); - case 234 /* JsxSelfClosingElement */: + case 236 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node); - case 235 /* JsxOpeningElement */: + case 237 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -23627,11 +24304,10 @@ var ts; grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } checkSourceElement(node.constraint); + getConstraintOfTypeParameter(getDeclaredTypeOfTypeParameter(getSymbolOfNode(node))); if (produceDiagnostics) { - checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } - // TODO: Check multiple declarations are identical } function checkParameter(node) { // Grammar checking @@ -23662,8 +24338,8 @@ var ts; return false; } return node.kind === 143 /* MethodDeclaration */ || - node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */; + node.kind === 215 /* FunctionDeclaration */ || + node.kind === 175 /* FunctionExpression */; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { @@ -23677,12 +24353,12 @@ var ts; } return -1; } - function isInLegalTypePredicatePosition(node) { + function isInLegalParameterTypePredicatePosition(node) { switch (node.parent.kind) { - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: case 147 /* CallSignature */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 152 /* FunctionType */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: @@ -23690,12 +24366,24 @@ var ts; } return false; } + function isInLegalThisTypePredicatePosition(node) { + if (isInLegalParameterTypePredicatePosition(node)) { + return true; + } + switch (node.parent.kind) { + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 145 /* GetAccessor */: + return node === node.parent.type; + } + return false; + } function checkSignatureDeclaration(node) { // Grammar checking if (node.kind === 149 /* IndexSignature */) { checkGrammarIndexSignature(node); } - else if (node.kind === 152 /* FunctionType */ || node.kind === 213 /* FunctionDeclaration */ || node.kind === 153 /* ConstructorType */ || + else if (node.kind === 152 /* FunctionType */ || node.kind === 215 /* FunctionDeclaration */ || node.kind === 153 /* ConstructorType */ || node.kind === 147 /* CallSignature */ || node.kind === 144 /* Constructor */ || node.kind === 148 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); @@ -23704,9 +24392,14 @@ var ts; ts.forEach(node.parameters, checkParameter); if (node.type) { if (node.type.kind === 150 /* TypePredicate */) { - var typePredicate = getSignatureFromDeclaration(node).typePredicate; + var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + if (!returnType || !(returnType.flags & 134217728 /* PredicateType */)) { + return; + } + var typePredicate = returnType.predicate; var typePredicateNode = node.type; - if (isInLegalTypePredicatePosition(typePredicateNode)) { + checkSourceElement(typePredicateNode); + if (ts.isIdentifierTypePredicate(typePredicate)) { if (typePredicate.parameterIndex >= 0) { if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); @@ -23722,8 +24415,8 @@ var ts; if (hasReportedError) { break; } - if (param.name.kind === 161 /* ObjectBindingPattern */ || - param.name.kind === 162 /* ArrayBindingPattern */) { + if (param.name.kind === 163 /* ObjectBindingPattern */ || + param.name.kind === 164 /* ArrayBindingPattern */) { (function checkBindingPattern(pattern) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; @@ -23733,8 +24426,8 @@ var ts; hasReportedError = true; break; } - else if (element.name.kind === 162 /* ArrayBindingPattern */ || - element.name.kind === 161 /* ObjectBindingPattern */) { + else if (element.name.kind === 164 /* ArrayBindingPattern */ || + element.name.kind === 163 /* ObjectBindingPattern */) { checkBindingPattern(element.name); } } @@ -23746,9 +24439,6 @@ var ts; } } } - else { - error(typePredicateNode, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); - } } else { checkSourceElement(node.type); @@ -23789,7 +24479,7 @@ var ts; checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 215 /* InterfaceDeclaration */) { + if (node.kind === 217 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind @@ -23839,7 +24529,7 @@ var ts; // Grammar checking checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration - checkFunctionLikeDeclaration(node); + checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. if (node.flags & 128 /* Abstract */ && node.body) { @@ -23866,7 +24556,7 @@ var ts; return; } function isSuperCallExpression(n) { - return n.kind === 168 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; + return n.kind === 170 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; } function containsSuperCallAsComputedPropertyName(n) { return n.name && containsSuperCall(n.name); @@ -23887,7 +24577,7 @@ var ts; if (n.kind === 97 /* ThisKeyword */) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 173 /* FunctionExpression */ && n.kind !== 213 /* FunctionDeclaration */) { + else if (n.kind !== 175 /* FunctionExpression */ && n.kind !== 215 /* FunctionDeclaration */) { ts.forEachChild(n, markThisReferencesAsErrors); } } @@ -23922,7 +24612,7 @@ var ts; var superCallStatement; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 195 /* ExpressionStatement */ && isSuperCallExpression(statement.expression)) { + if (statement.kind === 197 /* ExpressionStatement */ && isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; } @@ -23948,6 +24638,8 @@ var ts; if (produceDiagnostics) { // Grammar checking accessors checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); if (node.kind === 145 /* GetAccessor */) { if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288 /* HasImplicitReturn */)) { if (node.flags & 1048576 /* HasExplicitReturn */) { @@ -23960,6 +24652,12 @@ var ts; } } } + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 136 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } if (!ts.hasDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. @@ -23982,18 +24680,32 @@ var ts; } getTypeOfAccessors(getSymbolOfNode(node)); } - checkFunctionLikeDeclaration(node); + if (node.parent.kind !== 167 /* ObjectLiteralExpression */) { + checkSourceElement(node.body); + } + else { + checkNodeDeferred(node); + } + } + function checkAccessorDeferred(node) { + checkSourceElement(node.body); } function checkMissingDeclaration(node) { checkDecorators(node); } - function checkTypeArgumentConstraints(typeParameters, typeArguments) { + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var typeArguments; + var mapper; var result = true; for (var i = 0; i < typeParameters.length; i++) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { + if (!typeArguments) { + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + mapper = createTypeMapper(typeParameters, typeArguments); + } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; @@ -24059,7 +24771,7 @@ var ts; var signaturesToCheck; // Unnamed (call\construct) signatures in interfaces are inherited and not shadowed so examining just node symbol won't give complete answer. // Use declaring type to obtain full list of signatures. - if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 215 /* InterfaceDeclaration */) { + if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 217 /* InterfaceDeclaration */) { ts.Debug.assert(signatureDeclarationNode.kind === 147 /* CallSignature */ || signatureDeclarationNode.kind === 148 /* ConstructSignature */); var signatureKind = signatureDeclarationNode.kind === 147 /* CallSignature */ ? 0 /* Call */ : 1 /* Construct */; var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); @@ -24071,7 +24783,7 @@ var ts; } for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { var otherSignature = signaturesToCheck_1[_i]; - if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { + if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature, /*ignoreReturnTypes*/ false)) { return; } } @@ -24081,9 +24793,9 @@ var ts; var flags = ts.getCombinedNodeFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 215 /* InterfaceDeclaration */ && - n.parent.kind !== 214 /* ClassDeclaration */ && - n.parent.kind !== 186 /* ClassExpression */ && + if (n.parent.kind !== 217 /* InterfaceDeclaration */ && + n.parent.kind !== 216 /* ClassDeclaration */ && + n.parent.kind !== 188 /* ClassExpression */ && ts.isInAmbientContext(n)) { if (!(flags & 4 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported @@ -24164,16 +24876,23 @@ var ts; seen = c === node; } }); - if (subsequentNode) { + // We may be here because of some extra junk between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - // the only situation when this is possible (same kind\same name but different symbol) - mixed static and instance class members - ts.Debug.assert(node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */); - ts.Debug.assert((node.flags & 64 /* Static */) !== (subsequentNode.flags & 64 /* Static */)); - var diagnostic = node.flags & 64 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); + var reportError = (node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) && + (node.flags & 64 /* Static */) !== (subsequentNode.flags & 64 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = node.flags & 64 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } return; } else if (ts.nodeIsPresent(subsequentNode.body)) { @@ -24206,7 +24925,7 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 215 /* InterfaceDeclaration */ || node.parent.kind === 155 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 217 /* InterfaceDeclaration */ || node.parent.kind === 155 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -24217,7 +24936,7 @@ var ts; // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one previousDeclaration = undefined; } - if (node.kind === 213 /* FunctionDeclaration */ || node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */ || node.kind === 144 /* Constructor */) { + if (node.kind === 215 /* FunctionDeclaration */ || node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */ || node.kind === 144 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -24288,7 +25007,7 @@ var ts; // The implementation is completely unrelated to the specialized signature, yet we do not check this. for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { var signature = signatures_3[_a]; - if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { + if (!signature.hasStringLiterals && !isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; } @@ -24357,16 +25076,16 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return 2097152 /* ExportType */; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return d.name.kind === 9 /* StringLiteral */ || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ : 4194304 /* ExportNamespace */; - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: var result = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); @@ -24587,6 +25306,8 @@ var ts; error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } + // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. + checkReturnTypeAnnotationAsExpression(node); // Validate the promise constructor type. var promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { @@ -24594,10 +25315,10 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var promiseName = ts.getEntityNameFromTypeNode(node.type); - var root = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, root.text, 107455 /* Value */); + var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); + var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455 /* Value */); if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, getFullyQualifiedName(promiseConstructor)); + error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); return unknownType; } // Get and return the awaited type of the return type. @@ -24614,7 +25335,7 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); @@ -24662,23 +25383,10 @@ var ts; * an expression if it is a type reference to a type with a value declaration. */ function checkTypeAnnotationAsExpression(node) { - switch (node.kind) { - case 141 /* PropertyDeclaration */: - checkTypeNodeAsExpression(node.type); - break; - case 138 /* Parameter */: - checkTypeNodeAsExpression(node.type); - break; - case 143 /* MethodDeclaration */: - checkTypeNodeAsExpression(node.type); - break; - case 145 /* GetAccessor */: - checkTypeNodeAsExpression(node.type); - break; - case 146 /* SetAccessor */: - checkTypeNodeAsExpression(ts.getSetAccessorTypeAnnotationNode(node)); - break; - } + checkTypeNodeAsExpression(node.type); + } + function checkReturnTypeAnnotationAsExpression(node) { + checkTypeNodeAsExpression(node.type); } /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ function checkParameterTypeAnnotationsAsExpressions(node) { @@ -24704,17 +25412,18 @@ var ts; if (compilerOptions.emitDecoratorMetadata) { // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; case 143 /* MethodDeclaration */: - checkParameterTypeAnnotationsAsExpressions(node); - // fall-through - case 146 /* SetAccessor */: case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + checkParameterTypeAnnotationsAsExpressions(node); + checkReturnTypeAnnotationAsExpression(node); + break; case 141 /* PropertyDeclaration */: case 138 /* Parameter */: checkTypeAnnotationAsExpression(node); @@ -24729,13 +25438,13 @@ var ts; } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); + checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); } } - function checkFunctionLikeDeclaration(node) { + function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); var isAsync = ts.isAsyncFunctionLike(node); @@ -24756,7 +25465,13 @@ var ts; // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.getDeclarationOfKind(localSymbol, node.kind); + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.forEach(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(getSourceFile(declaration)) ? + declaration : undefined; }); // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); @@ -24770,13 +25485,9 @@ var ts; } } checkSourceElement(node.body); - if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { - var returnType = getTypeFromTypeNode(node.type); - var promisedType; - if (isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + if (!node.asteriskToken) { + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !node.type) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method @@ -24794,13 +25505,10 @@ var ts; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 192 /* Block */) { + if (node.kind === 194 /* Block */) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 219 /* ModuleBlock */) { - checkFunctionAndClassExpressionBodies(node); - } } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact @@ -24884,12 +25592,12 @@ var ts; return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 218 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (node.kind === 220 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 248 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 250 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -24924,7 +25632,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 211 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 213 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -24934,17 +25642,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 193 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 214 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 195 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 192 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 219 /* ModuleBlock */ || - container.kind === 218 /* ModuleDeclaration */ || - container.kind === 248 /* SourceFile */); + (container.kind === 194 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 221 /* ModuleBlock */ || + container.kind === 220 /* ModuleDeclaration */ || + container.kind === 250 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -25002,7 +25710,7 @@ var ts; checkExpressionCached(node.initializer); } } - if (node.kind === 163 /* BindingElement */) { + if (node.kind === 165 /* BindingElement */) { // check computed properties inside property names of binding elements if (node.propertyName && node.propertyName.kind === 136 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); @@ -25048,7 +25756,7 @@ var ts; if (node.kind !== 141 /* PropertyDeclaration */ && node.kind !== 140 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) { + if (node.kind === 213 /* VariableDeclaration */ || node.kind === 165 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); @@ -25071,7 +25779,7 @@ var ts; } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && node.parent.kind === 165 /* ObjectLiteralExpression */) { + if (node.modifiers && node.parent.kind === 167 /* ObjectLiteralExpression */) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -25092,7 +25800,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 194 /* EmptyStatement */) { + if (node.thenStatement.kind === 196 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -25112,12 +25820,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 214 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 214 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -25137,14 +25845,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 214 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); // There may be a destructuring assignment on the left side - if (varExpr.kind === 164 /* ArrayLiteralExpression */ || varExpr.kind === 165 /* ObjectLiteralExpression */) { + if (varExpr.kind === 166 /* ArrayLiteralExpression */ || varExpr.kind === 167 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -25173,7 +25881,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 214 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -25187,7 +25895,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 164 /* ArrayLiteralExpression */ || varExpr.kind === 165 /* ObjectLiteralExpression */) { + if (varExpr.kind === 166 /* ArrayLiteralExpression */ || varExpr.kind === 167 /* 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 */)) { @@ -25383,7 +26091,13 @@ var ts; ts.Debug.assert(languageVersion < 2 /* ES6 */); // 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 = removeTypesFromUnionType(arrayOrStringType, 258 /* StringLike */, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); + var arrayType = arrayOrStringType; + if (arrayOrStringType.flags & 16384 /* Union */) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258 /* StringLike */); })); + } + else if (arrayOrStringType.flags & 258 /* StringLike */) { + arrayType = emptyUnionType; + } var hasStringConstituent = arrayOrStringType !== arrayType; var reportedError = false; if (hasStringConstituent) { @@ -25457,7 +26171,7 @@ var ts; error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { + else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || returnType.flags & 134217728 /* PredicateType */) { if (ts.isAsyncFunctionLike(func)) { var promisedType = getPromisedType(returnType); var awaitedType = checkAwaitedType(exprType, node.expression, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -25494,7 +26208,7 @@ var ts; var expressionTypeIsStringLike = someConstituentTypeHasKind(expressionType, 258 /* StringLike */); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 242 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 244 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -25506,17 +26220,17 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 241 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 243 /* CaseClause */) { var caseClause = clause; // TypeScript 1.0 spec (April 2014):5.9 // In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from the type of the 'switch' expression. var caseType = checkExpression(caseClause.expression); + var expressionTypeIsAssignableToCaseType = // Permit 'number[] | "foo"' to be asserted to 'string'. - if (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258 /* StringLike */)) { - return; - } - if (!isTypeAssignableTo(expressionType, caseType)) { - // check 'expressionType isAssignableTo caseType' failed, try the reversed check and report errors if it fails + (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258 /* StringLike */)) || + isTypeAssignableTo(expressionType, caseType); + if (!expressionTypeIsAssignableToCaseType) { + // 'expressionType is not assignable to caseType', try the reversed check and report errors if it fails checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); } } @@ -25531,7 +26245,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 207 /* LabeledStatement */ && current.label.text === node.label.text) { + if (current.kind === 209 /* LabeledStatement */ && current.label.text === node.label.text) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; @@ -25688,8 +26402,12 @@ var ts; } function checkClassExpression(node) { checkClassLikeDeclaration(node); + checkNodeDeferred(node); return getTypeOfSymbol(getSymbolOfNode(node)); } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + } function checkClassDeclaration(node) { if (!node.name && !(node.flags & 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -25814,7 +26532,7 @@ var ts; // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 128 /* Abstract */))) { - if (derivedClassDecl.kind === 186 /* ClassExpression */) { + if (derivedClassDecl.kind === 188 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -25932,7 +26650,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 215 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 217 /* InterfaceDeclaration */); if (symbol.declarations.length > 1) { if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { error(node.name, ts.Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); @@ -26006,7 +26724,8 @@ var ts; error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); } if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue++; + getNodeLinks(member).enumMemberValue = autoValue; + autoValue++; } } nodeLinks.flags |= 8192 /* EnumValuesComputed */; @@ -26041,7 +26760,7 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; @@ -26052,7 +26771,7 @@ var ts; case 50 /* TildeToken */: return ~value_1; } return undefined; - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -26077,11 +26796,11 @@ var ts; return undefined; case 8 /* NumericLiteral */: return +e.text; - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return evalConstant(e.expression); case 69 /* Identifier */: - case 167 /* ElementAccessExpression */: - case 166 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: + case 168 /* PropertyAccessExpression */: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; @@ -26094,7 +26813,7 @@ var ts; } else { var expression; - if (e.kind === 167 /* ElementAccessExpression */) { + if (e.kind === 169 /* ElementAccessExpression */) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9 /* StringLiteral */) { return undefined; @@ -26112,7 +26831,7 @@ var ts; if (current.kind === 69 /* Identifier */) { break; } - else if (current.kind === 166 /* PropertyAccessExpression */) { + else if (current.kind === 168 /* PropertyAccessExpression */) { current = current.expression; } else { @@ -26183,7 +26902,7 @@ var ts; var seenEnumMissingInitialInitializer = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 217 /* EnumDeclaration */) { + if (declaration.kind !== 219 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -26206,8 +26925,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 214 /* ClassDeclaration */ || - (declaration.kind === 213 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 216 /* ClassDeclaration */ || + (declaration.kind === 215 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -26263,7 +26982,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 214 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 216 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -26286,7 +27005,7 @@ var ts; if (node.kind === 135 /* QualifiedName */) { node = node.left; } - else if (node.kind === 166 /* PropertyAccessExpression */) { + else if (node.kind === 168 /* PropertyAccessExpression */) { node = node.expression; } else { @@ -26302,9 +27021,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 219 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; - if (node.parent.kind !== 248 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 228 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 221 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; + if (node.parent.kind !== 250 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 230 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -26327,7 +27046,7 @@ var ts; (symbol.flags & 793056 /* Type */ ? 793056 /* Type */ : 0) | (symbol.flags & 1536 /* Namespace */ ? 1536 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 230 /* ExportSpecifier */ ? + var message = node.kind === 232 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -26354,7 +27073,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 226 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -26411,8 +27130,8 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 219 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; - if (node.parent.kind !== 248 /* SourceFile */ && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 221 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; + if (node.parent.kind !== 250 /* SourceFile */ && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -26426,7 +27145,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 248 /* SourceFile */ && node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 218 /* ModuleDeclaration */) { + if (node.parent.kind !== 250 /* SourceFile */ && node.parent.kind !== 221 /* ModuleBlock */ && node.parent.kind !== 220 /* ModuleDeclaration */) { return grammarErrorOnFirstToken(node, errorMessage); } } @@ -26441,8 +27160,8 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 248 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 218 /* ModuleDeclaration */ && container.name.kind === 69 /* Identifier */) { + var container = node.parent.kind === 250 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 220 /* ModuleDeclaration */ && container.name.kind === 69 /* Identifier */) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } @@ -26468,15 +27187,6 @@ var ts; } } } - function getModuleStatements(node) { - if (node.kind === 248 /* SourceFile */) { - return node.statements; - } - if (node.kind === 218 /* ModuleDeclaration */ && node.body.kind === 219 /* ModuleBlock */) { - return node.body.statements; - } - return emptyArray; - } function hasExportedMembers(moduleSymbol) { for (var id in moduleSymbol.exports) { if (id !== "export=") { @@ -26494,13 +27204,43 @@ var ts; var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } + // Checks for export * conflicts + var exports = getExportsOfModule(moduleSymbol); + for (var id in exports) { + if (id === "__export") { + continue; + } + 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 */)) && (flags & 524288 /* TypeAlias */ ? declarations.length - 1 : declarations.length) > 1) { + var exportedDeclarations = ts.filter(declarations, isNotOverload); + if (exportedDeclarations.length > 1) { + for (var _i = 0, exportedDeclarations_1 = exportedDeclarations; _i < exportedDeclarations_1.length; _i++) { + var declaration = exportedDeclarations_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); + } + } + } + } links.exportsChecked = true; } + function isNotOverload(declaration) { + return declaration.kind !== 215 /* FunctionDeclaration */ || !!declaration.body; + } } function checkTypePredicate(node) { - if (!isInLegalTypePredicatePosition(node)) { + var parameterName = node.parameterName; + if (parameterName.kind === 69 /* Identifier */ && !isInLegalParameterTypePredicatePosition(node)) { error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); } + else if (parameterName.kind === 161 /* ThisType */) { + if (!isInLegalThisTypePredicatePosition(node)) { + error(node, ts.Diagnostics.A_this_based_type_predicate_is_only_allowed_within_a_class_or_interface_s_members_get_accessors_or_return_type_positions_for_functions_and_methods); + } + else { + getTypeFromThisTypeNode(parameterName); + } + } } function checkSourceElement(node) { if (!node) { @@ -26511,10 +27251,10 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessivly // hitting the cancellation token on every node we check. switch (kind) { - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 220 /* ModuleDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 215 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -26558,71 +27298,71 @@ var ts; return checkUnionOrIntersectionType(node); case 160 /* ParenthesizedType */: return checkSourceElement(node.type); - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 194 /* Block */: + case 221 /* ModuleBlock */: return checkBlock(node); - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return checkVariableStatement(node); - case 195 /* ExpressionStatement */: + case 197 /* ExpressionStatement */: return checkExpressionStatement(node); - case 196 /* IfStatement */: + case 198 /* IfStatement */: return checkIfStatement(node); - case 197 /* DoStatement */: + case 199 /* DoStatement */: return checkDoStatement(node); - case 198 /* WhileStatement */: + case 200 /* WhileStatement */: return checkWhileStatement(node); - case 199 /* ForStatement */: + case 201 /* ForStatement */: return checkForStatement(node); - case 200 /* ForInStatement */: + case 202 /* ForInStatement */: return checkForInStatement(node); - case 201 /* ForOfStatement */: + case 203 /* ForOfStatement */: return checkForOfStatement(node); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 204 /* ContinueStatement */: + case 205 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 204 /* ReturnStatement */: + case 206 /* ReturnStatement */: return checkReturnStatement(node); - case 205 /* WithStatement */: + case 207 /* WithStatement */: return checkWithStatement(node); - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: return checkSwitchStatement(node); - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: return checkLabeledStatement(node); - case 208 /* ThrowStatement */: + case 210 /* ThrowStatement */: return checkThrowStatement(node); - case 209 /* TryStatement */: + case 211 /* TryStatement */: return checkTryStatement(node); - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 163 /* BindingElement */: + case 165 /* BindingElement */: return checkBindingElement(node); - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: return checkClassDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 216 /* TypeAliasDeclaration */: + case 218 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: return checkImportDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return checkExportDeclaration(node); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return checkExportAssignment(node); - case 194 /* EmptyStatement */: + case 196 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 210 /* DebuggerStatement */: + case 212 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 231 /* MissingDeclaration */: + case 233 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -26635,102 +27375,29 @@ var ts; // Here, performing a full type check of the body of the function expression whilst in the process of // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. - function checkFunctionAndClassExpressionBodies(node) { - switch (node.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - checkFunctionExpressionOrObjectLiteralMethodBody(node); - break; - case 186 /* ClassExpression */: - ts.forEach(node.members, checkSourceElement); - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - if (ts.isObjectLiteralMethod(node)) { - checkFunctionExpressionOrObjectLiteralMethodBody(node); - } - break; - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - break; - case 205 /* WithStatement */: - checkFunctionAndClassExpressionBodies(node.expression); - break; - case 139 /* Decorator */: - case 138 /* Parameter */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 163 /* BindingElement */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 245 /* PropertyAssignment */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 170 /* TaggedTemplateExpression */: - case 183 /* TemplateExpression */: - case 190 /* TemplateSpan */: - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: - case 172 /* ParenthesizedExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 178 /* AwaitExpression */: - case 175 /* DeleteExpression */: - case 179 /* PrefixUnaryExpression */: - case 180 /* PostfixUnaryExpression */: - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 184 /* YieldExpression */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 193 /* VariableStatement */: - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 220 /* CaseBlock */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: - case 211 /* VariableDeclaration */: - case 212 /* VariableDeclarationList */: - case 214 /* ClassDeclaration */: - case 243 /* HeritageClause */: - case 188 /* ExpressionWithTypeArguments */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 227 /* ExportAssignment */: - case 248 /* SourceFile */: - case 240 /* JsxExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - case 235 /* JsxOpeningElement */: - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + checkAccessorDeferred(node); + break; + case 188 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + } } } function checkSourceFile(node) { @@ -26756,9 +27423,12 @@ var ts; emitExtends = false; emitDecorate = false; emitParam = false; + emitAwaiter = false; potentialThisCollisions.length = 0; + deferredNodes = []; ts.forEach(node.statements, checkSourceElement); - checkFunctionAndClassExpressionBodies(node); + checkDeferredNodes(); + deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -26818,7 +27488,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 205 /* WithStatement */ && node.parent.statement === node) { + if (node.parent.kind === 207 /* WithStatement */ && node.parent.statement === node) { return true; } node = node.parent; @@ -26841,25 +27511,25 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); break; - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } // fall through; this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -26868,7 +27538,7 @@ var ts; copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; - case 173 /* FunctionExpression */: + case 175 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -26918,10 +27588,10 @@ var ts; function isTypeDeclaration(node) { switch (node.kind) { case 137 /* TypeParameter */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 219 /* EnumDeclaration */: return true; } } @@ -26935,19 +27605,19 @@ var ts; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 166 /* PropertyAccessExpression */) { + while (node.parent && node.parent.kind === 168 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 188 /* ExpressionWithTypeArguments */; + return node.parent && node.parent.kind === 190 /* ExpressionWithTypeArguments */; } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { while (nodeOnRightSide.parent.kind === 135 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 221 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 223 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 227 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 229 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -26959,11 +27629,11 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 227 /* ExportAssignment */) { + if (entityName.parent.kind === 229 /* ExportAssignment */) { return resolveEntityName(entityName, /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 166 /* PropertyAccessExpression */) { + if (entityName.kind !== 168 /* PropertyAccessExpression */) { if (isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); @@ -26975,7 +27645,7 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 188 /* ExpressionWithTypeArguments */) { + if (entityName.parent.kind === 190 /* ExpressionWithTypeArguments */) { meaning = 793056 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -26988,9 +27658,9 @@ var ts; meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if ((entityName.parent.kind === 235 /* JsxOpeningElement */) || - (entityName.parent.kind === 234 /* JsxSelfClosingElement */) || - (entityName.parent.kind === 237 /* JsxClosingElement */)) { + else if ((entityName.parent.kind === 237 /* JsxOpeningElement */) || + (entityName.parent.kind === 236 /* JsxSelfClosingElement */) || + (entityName.parent.kind === 239 /* JsxClosingElement */)) { return getJsxElementTagSymbol(entityName.parent); } else if (ts.isExpression(entityName)) { @@ -27004,7 +27674,7 @@ var ts; var meaning = 107455 /* Value */ | 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 166 /* PropertyAccessExpression */) { + else if (entityName.kind === 168 /* PropertyAccessExpression */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); @@ -27026,7 +27696,7 @@ var ts; meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if (entityName.parent.kind === 238 /* JsxAttribute */) { + else if (entityName.parent.kind === 240 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } if (entityName.parent.kind === 150 /* TypePredicate */) { @@ -27046,12 +27716,12 @@ var ts; } if (node.kind === 69 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 227 /* ExportAssignment */ + return node.parent.kind === 229 /* ExportAssignment */ ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } - else if (node.parent.kind === 163 /* BindingElement */ && - node.parent.parent.kind === 161 /* ObjectBindingPattern */ && + else if (node.parent.kind === 165 /* BindingElement */ && + node.parent.parent.kind === 163 /* ObjectBindingPattern */ && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -27062,13 +27732,15 @@ var ts; } switch (node.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: case 135 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; + case 161 /* ThisType */: + return getTypeFromTypeNode(node).symbol; case 121 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; @@ -27080,14 +27752,14 @@ var ts; // External module name in an import declaration if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 222 /* ImportDeclaration */ || node.parent.kind === 228 /* ExportDeclaration */) && + ((node.parent.kind === 224 /* ImportDeclaration */ || node.parent.kind === 230 /* ExportDeclaration */) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } // Fall through case 8 /* NumericLiteral */: // index access - if (node.parent.kind === 167 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { + if (node.parent.kind === 169 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -27104,7 +27776,7 @@ var ts; // The function returns a value symbol of an identifier in the short-hand property assignment. // This is necessary as an identifier in short-hand property assignment can contains two meaning: // property name and property value. - if (location && location.kind === 246 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 248 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 107455 /* Value */); } return undefined; @@ -27207,6 +27879,30 @@ var ts; function isArgumentsLocalBinding(node) { return getReferencedValueSymbol(node) === argumentsSymbol; } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol) { + // module not found - be conservative + return true; + } + var hasExportAssignment = getExportAssignmentSymbol(moduleSymbol) !== undefined; + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455 /* Value */) + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455 /* Value */); + } + } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. function getReferencedExportContainer(node) { @@ -27224,11 +27920,11 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 248 /* SourceFile */) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 250 /* SourceFile */) { return parentSymbol.valueDeclaration; } for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 218 /* ModuleDeclaration */ || n.kind === 217 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { + if ((n.kind === 220 /* ModuleDeclaration */ || n.kind === 219 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { return n; } } @@ -27243,11 +27939,11 @@ var ts; } function isStatementWithLocals(node) { switch (node.kind) { - case 192 /* Block */: - case 220 /* CaseBlock */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 194 /* Block */: + case 222 /* CaseBlock */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: return true; } return false; @@ -27277,22 +27973,22 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 223 /* ImportEqualsDeclaration */: + case 225 /* ImportClause */: + case 226 /* NamespaceImport */: + case 228 /* ImportSpecifier */: + case 232 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node)); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return node.expression && node.expression.kind === 69 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 248 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 250 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -27354,7 +28050,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 247 /* EnumMember */) { + if (node.kind === 249 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -27446,17 +28142,6 @@ var ts; var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } - function instantiateSingleCallFunctionType(functionType, typeArguments) { - if (functionType === unknownType) { - return unknownType; - } - var signature = getSingleCallSignature(functionType); - if (!signature) { - return unknownType; - } - var instantiatedSignature = getSignatureInstantiation(signature, typeArguments); - return getOrCreateTypeFromSignature(instantiatedSignature); - } function createResolver() { return { getReferencedExportContainer: getReferencedExportContainer, @@ -27480,6 +28165,7 @@ var ts; getReferencedValueDeclaration: getReferencedValueDeclaration, getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, isArgumentsLocalBinding: isArgumentsLocalBinding, getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration }; @@ -27490,7 +28176,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 248 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 250 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -27503,10 +28189,11 @@ var ts; mergeSymbolTable(globals, file.locals); } }); + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); getSymbolLinks(unknownSymbol).type = unknownType; - globals[undefinedSymbol.name] = undefinedSymbol; // Initialize special types globalArrayType = getGlobalType("Array", /*arity*/ 1); globalObjectType = getGlobalType("Object"); @@ -27575,7 +28262,12 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + if (node.kind === 143 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } } else if (node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); @@ -27595,30 +28287,30 @@ var ts; case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 149 /* IndexSignature */: - case 218 /* ModuleDeclaration */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: - case 227 /* ExportAssignment */: + case 220 /* ModuleDeclaration */: + case 224 /* ImportDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 230 /* ExportDeclaration */: + case 229 /* ExportAssignment */: case 138 /* Parameter */: break; - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118 /* AsyncKeyword */) && - node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + node.parent.kind !== 221 /* ModuleBlock */ && node.parent.kind !== 250 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 193 /* VariableStatement */: - case 216 /* TypeAliasDeclaration */: - if (node.modifiers && node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 195 /* VariableStatement */: + case 218 /* TypeAliasDeclaration */: + if (node.modifiers && node.parent.kind !== 221 /* ModuleBlock */ && node.parent.kind !== 250 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74 /* ConstKeyword */) && - node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + node.parent.kind !== 221 /* ModuleBlock */ && node.parent.kind !== 250 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; @@ -27633,6 +28325,11 @@ var ts; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; switch (modifier.kind) { + case 74 /* ConstKeyword */: + if (node.kind !== 219 /* EnumDeclaration */ && node.parent.kind === 216 /* ClassDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74 /* ConstKeyword */)); + } + break; case 112 /* PublicKeyword */: case 111 /* ProtectedKeyword */: case 110 /* PrivateKeyword */: @@ -27657,7 +28354,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { + else if (node.parent.kind === 221 /* ModuleBlock */ || node.parent.kind === 250 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } else if (flags & 128 /* Abstract */) { @@ -27677,7 +28374,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { + else if (node.parent.kind === 221 /* ModuleBlock */ || node.parent.kind === 250 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); } else if (node.kind === 138 /* Parameter */) { @@ -27702,7 +28399,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 216 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } else if (node.kind === 138 /* Parameter */) { @@ -27717,13 +28414,13 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 216 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } else if (node.kind === 138 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219 /* ModuleBlock */) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 221 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 4 /* Ambient */; @@ -27733,11 +28430,11 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 214 /* ClassDeclaration */) { + if (node.kind !== 216 /* ClassDeclaration */) { if (node.kind !== 143 /* MethodDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); } - if (!(node.parent.kind === 214 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { + if (!(node.parent.kind === 216 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 64 /* Static */) { @@ -27782,7 +28479,7 @@ var ts; } return; } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && flags & 4 /* Ambient */) { + else if ((node.kind === 224 /* ImportDeclaration */ || node.kind === 223 /* ImportEqualsDeclaration */) && flags & 4 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 138 /* Parameter */ && (flags & 56 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { @@ -27798,9 +28495,9 @@ var ts; } switch (node.kind) { case 143 /* MethodDeclaration */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: if (!node.asteriskToken) { return false; } @@ -27866,7 +28563,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 174 /* ArrowFunction */) { + if (node.kind === 176 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -27934,7 +28631,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { var arg = args_1[_i]; - if (arg.kind === 187 /* OmittedExpression */) { + if (arg.kind === 189 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -28012,14 +28709,14 @@ var ts; return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 181 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { + if (computedPropertyName.expression.kind === 183 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */ || + ts.Debug.assert(node.kind === 215 /* FunctionDeclaration */ || + node.kind === 175 /* FunctionExpression */ || node.kind === 143 /* MethodDeclaration */); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); @@ -28043,20 +28740,25 @@ var ts; var GetAccessor = 2; var SetAccesor = 4; var GetOrSetAccessor = GetAccessor | SetAccesor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; + var _loop_1 = function(prop) { var name_16 = prop.name; - if (prop.kind === 187 /* OmittedExpression */ || + if (prop.kind === 189 /* OmittedExpression */ || name_16.kind === 136 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name_16); - continue; + return "continue"; } - if (prop.kind === 246 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 248 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; } + // Modifiers are never allowed on properties except for 'async' on a method declaration + ts.forEach(prop.modifiers, function (mod) { + if (mod.kind !== 118 /* AsyncKeyword */ || prop.kind !== 143 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + }); // ECMA-262 11.1.5 Object Initialiser // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and @@ -28066,7 +28768,7 @@ var ts; // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; - if (prop.kind === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */) { + if (prop.kind === 247 /* PropertyAssignment */ || prop.kind === 248 /* ShorthandPropertyAssignment */) { // Grammar checking for computedPropertName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name_16.kind === 8 /* NumericLiteral */) { @@ -28092,27 +28794,33 @@ var ts; else { var existingKind = seen[name_16.text]; if (currentKind === Property && existingKind === Property) { - continue; + return "continue"; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[name_16.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return { value: grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return { value: grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } + }; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var state_1 = _loop_1(prop); + if (typeof state_1 === "object") return state_1.value + if (state_1 === "continue") continue; } } function checkGrammarJsxElement(node) { var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 239 /* JsxSpreadAttribute */) { + if (attr.kind === 241 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; @@ -28124,7 +28832,7 @@ var ts; return grammarErrorOnNode(name_17, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 240 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 242 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -28133,24 +28841,35 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 212 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 214 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { - if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 202 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } - var firstDeclaration = variableList.declarations[0]; + var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 202 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 202 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -28211,7 +28930,7 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 165 /* ObjectLiteralExpression */) { + if (node.parent.kind === 167 /* ObjectLiteralExpression */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } @@ -28235,7 +28954,7 @@ var ts; return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); } } - else if (node.parent.kind === 215 /* InterfaceDeclaration */) { + else if (node.parent.kind === 217 /* InterfaceDeclaration */) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); } else if (node.parent.kind === 155 /* TypeLiteral */) { @@ -28249,11 +28968,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: if (node.label && current.label.text === node.label.text) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 202 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 204 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -28261,8 +28980,8 @@ var ts; return false; } break; - case 206 /* SwitchStatement */: - if (node.kind === 203 /* BreakStatement */ && !node.label) { + case 208 /* SwitchStatement */: + if (node.kind === 205 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -28277,13 +28996,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 203 /* BreakStatement */ + var message = node.kind === 205 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 203 /* BreakStatement */ + var message = node.kind === 205 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -28295,7 +29014,7 @@ var ts; if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } - if (node.name.kind === 162 /* ArrayBindingPattern */ || node.name.kind === 161 /* ObjectBindingPattern */) { + if (node.name.kind === 164 /* ArrayBindingPattern */ || node.name.kind === 163 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -28305,7 +29024,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 200 /* ForInStatement */ && node.parent.parent.kind !== 201 /* ForOfStatement */) { + if (node.parent.parent.kind !== 202 /* ForInStatement */ && node.parent.parent.kind !== 203 /* ForOfStatement */) { if (ts.isInAmbientContext(node)) { if (node.initializer) { // Error on equals token which immediate precedes the initializer @@ -28322,7 +29041,7 @@ var ts; } } } - var checkLetConstNames = languageVersion >= 2 /* ES6 */ && (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding @@ -28333,7 +29052,7 @@ var ts; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 69 /* Identifier */) { - if (name.text === "let") { + if (name.originalKeywordKind === 108 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -28341,7 +29060,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 189 /* OmittedExpression */) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -28358,15 +29077,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 198 /* IfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: + case 207 /* WithStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: return false; - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -28381,23 +29100,6 @@ var ts; } } } - function isIntegerLiteral(expression) { - if (expression.kind === 179 /* PrefixUnaryExpression */) { - var unaryExpression = expression; - if (unaryExpression.operator === 35 /* PlusToken */ || unaryExpression.operator === 36 /* MinusToken */) { - expression = unaryExpression.operand; - } - } - if (expression.kind === 8 /* NumericLiteral */) { - // Allows for scientific notation since literalExpression.text was formed by - // coercing a number to a string. Sometimes this coercion can yield a string - // in scientific notation. - // We also don't need special logic for hex because a hex integer is converted - // to decimal when it is coerced. - return /^[0-9]+([eE]\+?[0-9]+)?$/.test(expression.text); - } - return false; - } function hasParseDiagnostics(sourceFile) { return sourceFile.parseDiagnostics.length > 0; } @@ -28422,10 +29124,6 @@ var ts; return true; } } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 /* Identifier */ && - (node.text === "eval" || node.text === "arguments"); - } function checkGrammarConstructorTypeParameters(node) { if (node.typeParameters) { return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); @@ -28443,15 +29141,21 @@ var ts; return true; } } - else if (node.parent.kind === 215 /* InterfaceDeclaration */) { + else if (node.parent.kind === 217 /* InterfaceDeclaration */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } } else if (node.parent.kind === 155 /* TypeLiteral */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } } if (ts.isInAmbientContext(node) && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); @@ -28470,12 +29174,12 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 215 /* InterfaceDeclaration */ || - node.kind === 216 /* TypeAliasDeclaration */ || - node.kind === 222 /* ImportDeclaration */ || - node.kind === 221 /* ImportEqualsDeclaration */ || - node.kind === 228 /* ExportDeclaration */ || - node.kind === 227 /* ExportAssignment */ || + if (node.kind === 217 /* InterfaceDeclaration */ || + node.kind === 218 /* TypeAliasDeclaration */ || + node.kind === 224 /* ImportDeclaration */ || + node.kind === 223 /* ImportEqualsDeclaration */ || + node.kind === 230 /* ExportDeclaration */ || + node.kind === 229 /* ExportAssignment */ || (node.flags & 4 /* Ambient */) || (node.flags & (2 /* Export */ | 512 /* Default */))) { return false; @@ -28485,7 +29189,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 193 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 195 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -28511,7 +29215,7 @@ var ts; // to prevent noisyness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 192 /* Block */ || node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { + if (node.parent.kind === 194 /* Block */ || node.parent.kind === 221 /* ModuleBlock */ || node.parent.kind === 250 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -28536,21 +29240,293 @@ var ts; return true; } } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); /// /* @internal */ var ts; +(function (ts) { + var nullSourceMapWriter; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitStart: function (range) { }, + emitEnd: function (range) { }, + emitPos: function (pos) { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; }, + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + var currentSourceFile; + var sourceMapDir; // The directory in which sourcemap will be + // Current source map file and its index in the sources list + var sourceMapSourceIndex; + // Last recorded and encoded spans + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan; + var lastEncodedNameIndex; + // Source map data + var sourceMapData; + return { + getSourceMapData: function () { return sourceMapData; }, + setSourceFile: setSourceFile, + emitPos: emitPos, + emitStart: emitStart, + emitEnd: emitEnd, + getText: getText, + getSourceMappingURL: getSourceMappingURL, + initialize: initialize, + reset: reset + }; + function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (sourceMapData) { + reset(); + } + currentSourceFile = undefined; + // Current source map file and its index in the sources list + sourceMapSourceIndex = -1; + // Last recorded and encoded spans + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + lastEncodedNameIndex = 0; + // Initialize source map data + sourceMapData = { + sourceMapFilePath: sourceMapFilePath, + jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, + sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, + sourceMapDecodedMappings: [] + }; + // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the + // relative paths of the sources list in the sourcemap + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (!isBundledEmit) { + ts.Debug.assert(sourceFiles.length === 1); + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); + } + } + function reset() { + currentSourceFile = undefined; + sourceMapDir = undefined; + sourceMapSourceIndex = undefined; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = undefined; + lastEncodedNameIndex = undefined; + sourceMapData = undefined; + } + // Encoding for sourcemap span + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + // Line/Comma delimiters + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + // Emit comma to separate the entry + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + // Emit line delimiters + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + // 1. Relative Column 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + // 2. Relative sourceIndex + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + // 3. Relative sourceLine 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + // 4. Relative sourceColumn 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + // 5. Relative namePosition 0 based + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + } + function emitPos(pos) { + if (pos === -1) { + return; + } + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + // Convert the location to be one-based. + sourceLinePos.line++; + sourceLinePos.character++; + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + // If this location wasn't recorded or the location in source is going backwards, record the span + if (!lastRecordedSourceMapSpan || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || + (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && + (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || + (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + // Encode the last recordedSpan before assigning new + encodeLastRecordedSourceMapSpan(); + // New span + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + sourceIndex: sourceMapSourceIndex + }; + } + else { + // Take the new pos instead since there is no change in emittedLine and column since last location + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + } + function emitStart(range) { + var rangeHasDecorators = !!range.decorators; + emitPos(range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1); + } + function emitEnd(range) { + emitPos(range.end); + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + // Add the file to tsFilePaths + // If sourceroot option: Use the relative path corresponding to the common directory path + // otherwise source locations relative to map file location + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + if (sourceMapSourceIndex === -1) { + sourceMapSourceIndex = sourceMapData.sourceMapSources.length; + sourceMapData.sourceMapSources.push(source); + // The one that can be used from program to get the actual source file + sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + if (compilerOptions.inlineSources) { + sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + } + } + } + function getText() { + encodeLastRecordedSourceMapSpan(); + return ts.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent + }); + } + function getSourceMappingURL() { + if (compilerOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var base64SourceMapText = ts.convertToBase64(getText()); + return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; + } + else { + return sourceMapData.jsSourceMappingURL; + } + } + } + ts.createSourceMapWriter = createSourceMapWriter; + var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function base64FormatEncode(inValue) { + if (inValue < 64) { + return base64Chars.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + function base64VLQFormatEncode(inValue) { + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + // Encode 5 bits at a time starting from least significant bits + var encodedStr = ""; + do { + var currentDigit = inValue & 31; // 11111 + inValue = inValue >> 5; + if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } +})(ts || (ts = {})); +/// +/* @internal */ +var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var diagnostics = []; - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); - emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); - return diagnostics; + var declarationDiagnostics = ts.createDiagnosticCollection(); + ts.forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); + return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName); + function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { + var declarationFilePath = _a.declarationFilePath; + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -28568,103 +29544,79 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare = !root; + var noDeclare; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. // Collecting this separately because reference paths need to be first thing in the declaration file // and we could be collecting these paths from multiple files into single one with --out option var referencePathsOutput = ""; - if (root) { - // Emitting just a single file, so emit references in this file only + // Emit references corresponding to each file + var emittedReferencedFiles = []; + var addedGlobalFileReference = false; + var allSourcesModuleElementDeclarationEmitInfo = []; + ts.forEach(sourceFiles, function (sourceFile) { + // Dont emit for javascript file + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + // Check what references need to be added if (!compilerOptions.noResolve) { - var addedGlobalFileReference = false; - ts.forEach(root.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); - // All the references that are not going to be part of same file - if (referencedFile && ((referencedFile.flags & 4096 /* DeclarationFile */) || - ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || - !addedGlobalFileReference)) { - writeReferencePath(referencedFile); - if (!ts.isExternalModuleOrDeclarationFile(referencedFile)) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + // Emit reference in dts, if the file reference was not already emitted + if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { + // Add a reference to generated dts file, + // global file reference is added only + // - if it is not bundled emit (because otherwise it would be self reference) + // - and it is not already added + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } + emittedReferencedFiles.push(referencedFile); } }); } - emitSourceFile(root); + if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { + noDeclare = false; + emitSourceFile(sourceFile); + } + else if (ts.isExternalModule(sourceFile)) { + noDeclare = true; + write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); + writeLine(); + increaseIndent(); + emitSourceFile(sourceFile); + decreaseIndent(); + write("}"); + writeLine(); + } // create asynchronous output for the importDeclarations if (moduleElementDeclarationEmitInfo.length) { var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222 /* ImportDeclaration */); + if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { + ts.Debug.assert(aliasEmitInfo.node.kind === 224 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0); + ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + increaseIndent(); + } writeImportDeclaration(aliasEmitInfo.node); aliasEmitInfo.asynchronousOutput = writer.getText(); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + decreaseIndent(); + } } }); setWriter(oldWriter); + allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); + moduleElementDeclarationEmitInfo = []; } - } - else { - // Emit references corresponding to this file - var emittedReferencedFiles = []; - var prevModuleElementDeclarationEmitInfo = []; - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!ts.isDeclarationFile(sourceFile)) { - // Check what references need to be added - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - // If the reference file is a declaration file, emit that reference - if (referencedFile && (ts.isDeclarationFile(referencedFile) && - !ts.contains(emittedReferencedFiles, referencedFile))) { - writeReferencePath(referencedFile); - emittedReferencedFiles.push(referencedFile); - } - }); - } - } - if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) { - noDeclare = false; - emitSourceFile(sourceFile); - } - else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; - write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - write("}"); - writeLine(); - // create asynchronous output for the importDeclarations - if (moduleElementDeclarationEmitInfo.length) { - var oldWriter = writer; - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222 /* ImportDeclaration */); - createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 1); - increaseIndent(); - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - decreaseIndent(); - } - }); - setWriter(oldWriter); - } - prevModuleElementDeclarationEmitInfo = prevModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - }); - moduleElementDeclarationEmitInfo = moduleElementDeclarationEmitInfo.concat(prevModuleElementDeclarationEmitInfo); - } + }); return { reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: moduleElementDeclarationEmitInfo, + moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), referencePathsOutput: referencePathsOutput }; @@ -28707,10 +29659,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 211 /* VariableDeclaration */) { + if (declaration.kind === 213 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 225 /* NamedImports */ || declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 223 /* ImportClause */) { + else if (declaration.kind === 227 /* NamedImports */ || declaration.kind === 228 /* ImportSpecifier */ || declaration.kind === 225 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -28728,7 +29680,7 @@ var ts; // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, // we would write alias foo declaration when we visit it since it would now be marked as visible if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 222 /* ImportDeclaration */) { + if (moduleElementEmitInfo.node.kind === 224 /* ImportDeclaration */) { // we have to create asynchronous output only after we have collected complete information // because it is possible to enable multiple bindings as asynchronously visible moduleElementEmitInfo.isVisible = true; @@ -28738,12 +29690,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 220 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 220 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -28766,10 +29718,10 @@ var ts; var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); if (errorInfo) { if (errorInfo.typeName) { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); } else { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); } } } @@ -28779,7 +29731,8 @@ var ts; } function reportInaccessibleThisError() { if (errorNameNode) { - diagnostics.push(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { @@ -28850,10 +29803,10 @@ var ts; case 120 /* BooleanKeyword */: case 131 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 97 /* ThisKeyword */: - case 9 /* StringLiteral */: + case 161 /* ThisType */: + case 162 /* StringLiteralType */: return writeTextOfNode(currentText, type); - case 188 /* ExpressionWithTypeArguments */: + case 190 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); case 151 /* TypeReference */: return emitTypeReference(type); @@ -28896,13 +29849,13 @@ var ts; function emitEntityName(entityName) { var visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 221 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); + entityName.parent.kind === 223 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 166 /* PropertyAccessExpression */); + ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 168 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -28980,7 +29933,8 @@ var ts; } var count = 0; while (true) { - var name_18 = baseName + "_" + (++count); + count++; + var name_18 = baseName + "_" + count; if (!ts.hasProperty(currentIdentifiers, name_18)) { return name_18; } @@ -29026,10 +29980,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 221 /* ImportEqualsDeclaration */ || - (node.parent.kind === 248 /* SourceFile */ && isCurrentFileExternalModule)) { + else if (node.kind === 223 /* ImportEqualsDeclaration */ || + (node.parent.kind === 250 /* SourceFile */ && isCurrentFileExternalModule)) { var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248 /* SourceFile */) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 250 /* SourceFile */) { // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, @@ -29039,7 +29993,7 @@ var ts; }); } else { - if (node.kind === 222 /* ImportDeclaration */) { + if (node.kind === 224 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -29057,23 +30011,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return writeVariableStatement(node); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: return writeClassDeclaration(node); - case 216 /* TypeAliasDeclaration */: + case 218 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -29081,7 +30035,7 @@ var ts; } function emitModuleElementDeclarationFlags(node) { // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent.kind === 248 /* SourceFile */) { + if (node.parent.kind === 250 /* SourceFile */) { // If the node is exported if (node.flags & 2 /* Export */) { write("export "); @@ -29089,7 +30043,7 @@ var ts; if (node.flags & 512 /* Default */) { write("default "); } - else if (node.kind !== 215 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 217 /* InterfaceDeclaration */ && !noDeclare) { write("declare "); } } @@ -29124,7 +30078,7 @@ var ts; } else { write("require("); - writeTextOfNode(currentText, ts.getExternalModuleImportEqualsDeclarationExpression(node)); + emitExternalModuleSpecifier(node); write(");"); } writer.writeLine(); @@ -29138,7 +30092,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 224 /* NamespaceImport */) { + if (namedBindings.kind === 226 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -29166,7 +30120,7 @@ var ts; // If the default binding was emitted, write the separated write(", "); } - if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 226 /* NamespaceImport */) { write("* as "); writeTextOfNode(currentText, node.importClause.namedBindings.name); } @@ -29178,13 +30132,22 @@ var ts; } write(" from "); } - emitExternalModuleSpecifier(node.moduleSpecifier); + emitExternalModuleSpecifier(node); write(";"); writer.writeLine(); } - function emitExternalModuleSpecifier(moduleSpecifier) { - if (moduleSpecifier.kind === 9 /* StringLiteral */ && (!root) && (compilerOptions.out || compilerOptions.outFile)) { - var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, moduleSpecifier.parent); + function emitExternalModuleSpecifier(parent) { + var moduleSpecifier; + if (parent.kind === 223 /* ImportEqualsDeclaration */) { + var node = parent; + moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); + } + else { + var node = parent; + moduleSpecifier = node.moduleSpecifier; + } + if (moduleSpecifier.kind === 9 /* StringLiteral */ && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { + var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); if (moduleName) { write("\""); write(moduleName); @@ -29221,7 +30184,7 @@ var ts; } if (node.moduleSpecifier) { write(" from "); - emitExternalModuleSpecifier(node.moduleSpecifier); + emitExternalModuleSpecifier(node); } write(";"); writer.writeLine(); @@ -29236,7 +30199,7 @@ var ts; write("module "); } writeTextOfNode(currentText, node.name); - while (node.body.kind !== 219 /* ModuleBlock */) { + while (node.body.kind !== 221 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentText, node.name); @@ -29331,10 +30294,10 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; case 148 /* ConstructSignature */: @@ -29348,14 +30311,14 @@ var ts; if (node.parent.flags & 64 /* Static */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 216 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -29389,7 +30352,7 @@ var ts; function getHeritageClauseVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + if (node.parent.parent.kind === 216 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : @@ -29473,7 +30436,7 @@ var ts; function emitVariableDeclaration(node) { // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted // so there is no check needed to see if declaration is visible - if (node.kind !== 211 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + if (node.kind !== 213 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } @@ -29495,7 +30458,7 @@ var ts; } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 211 /* VariableDeclaration */) { + if (node.kind === 213 /* VariableDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29511,7 +30474,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 216 /* ClassDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29543,7 +30506,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 189 /* OmittedExpression */) { elements.push(element); } } @@ -29685,13 +30648,13 @@ var ts; // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 215 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } else if (node.kind === 143 /* MethodDeclaration */) { emitClassMemberDeclarationFlags(node); } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 215 /* FunctionDeclaration */) { write("function "); writeTextOfNode(currentText, node.name); } @@ -29712,6 +30675,8 @@ var ts; emitSignatureDeclaration(node); } function emitSignatureDeclaration(node) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; // Construct signature or constructor type write new Signature if (node.kind === 148 /* ConstructSignature */ || node.kind === 153 /* ConstructorType */) { write("new "); @@ -29723,8 +30688,6 @@ var ts; else { write("("); } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; // Parameters emitCommaList(node.parameters, emitParameterDeclaration); if (node.kind === 149 /* IndexSignature */) { @@ -29780,7 +30743,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 216 /* ClassDeclaration */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -29794,7 +30757,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -29872,7 +30835,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 216 /* ClassDeclaration */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29885,7 +30848,7 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29897,12 +30860,12 @@ var ts; } function emitBindingPattern(bindingPattern) { // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 161 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 163 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 162 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 164 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -29913,15 +30876,7 @@ var ts; } } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.kind === 187 /* OmittedExpression */) { + if (bindingElement.kind === 189 /* OmittedExpression */) { // If bindingElement is an omittedExpression (i.e. containing elision), // we will emit blank space (although this may differ from users' original code, // it allows emitSeparatedList to write separator appropriately) @@ -29930,7 +30885,7 @@ var ts; // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 163 /* BindingElement */) { + else if (bindingElement.kind === 165 /* BindingElement */) { if (bindingElement.propertyName) { // bindingElement has propertyName property in the following case: // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" @@ -29969,20 +30924,20 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: - case 218 /* ModuleDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 215 /* InterfaceDeclaration */: - case 214 /* ClassDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: + case 215 /* FunctionDeclaration */: + case 220 /* ModuleDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 217 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 219 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: // Import declaration without import clause is visible, otherwise it is not visible return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return emitExportDeclaration(node); case 144 /* Constructor */: case 143 /* MethodDeclaration */: @@ -29998,35 +30953,57 @@ var ts; case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return emitPropertyDeclaration(node); - case 247 /* EnumMember */: + case 249 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return emitExportAssignment(node); - case 248 /* SourceFile */: + case 250 /* SourceFile */: return emitSourceFile(node); } } - function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 4096 /* DeclarationFile */ - ? referencedFile.fileName // Declaration file, use declaration file name - : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) - ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file - : ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; // Global out file - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ false); - referencePathsOutput += "/// " + newLine; + /** + * Adds the reference to referenced file, returns true if global file reference was emitted + * @param referencedFile + * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not + */ + function writeReferencePath(referencedFile, addBundledFileReference) { + var declFileName; + var addedBundledEmitReference = false; + if (ts.isDeclarationFile(referencedFile)) { + // Declaration file, use declaration file name + declFileName = referencedFile.fileName; + } + else { + // Get the declaration file path + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + } + if (declFileName) { + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + referencePathsOutput += "/// " + newLine; + } + return addedBundledEmitReference; + function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path + if (isBundledEmit && !addBundledFileReference) { + return; + } + ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); + declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; + addedBundledEmitReference = isBundledEmit; + } } } /* @internal */ - function writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); - // TODO(shkamat): Should we not write any declaration file if any of them can produce error, - // or should we just not write this file like we are doing now - if (!emitDeclarationResult.reportedDeclarationError) { + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; + if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); + ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM); } + return emitSkipped; function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { var appliedSyncOutputPos = 0; var declarationOutput = ""; @@ -30045,14 +31022,11 @@ var ts; ts.writeDeclarationFile = writeDeclarationFile; })(ts || (ts = {})); /// +/// /// /* @internal */ var ts; (function (ts) { - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); - } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; function getResolvedExternalModuleName(host, file) { return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); } @@ -30345,43 +31319,17 @@ var ts; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\n return new Promise(function (resolve, reject) {\n generator = generator.call(thisArg, _arguments);\n function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\n function onfulfill(value) { try { step(\"next\", value); } catch (e) { reject(e); } }\n function onreject(value) { try { step(\"throw\", value); } catch (e) { reject(e); } }\n function step(verb, value) {\n var result = generator[verb](value);\n result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\n }\n step(\"next\", void 0);\n });\n};"; var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || 0 /* ES3 */; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; - var diagnostics = []; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emitSkipped = false; var newLine = host.getNewLine(); - var jsxDesugaring = host.getCompilerOptions().jsx !== 1 /* Preserve */; - var shouldEmitJsx = function (s) { return (s.languageVariant === 1 /* JSX */ && !jsxDesugaring); }; - var outFile = compilerOptions.outFile || compilerOptions.out; var emitJavaScript = createFileEmitter(); - if (targetSourceFile === undefined) { - if (outFile) { - emitFile(outFile); - } - else { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - } - } - else { - // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service) - if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!ts.isDeclarationFile(targetSourceFile) && outFile) { - emitFile(outFile); - } - } - // Sort and make the unique list of diagnostics - diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { - emitSkipped: false, - diagnostics: diagnostics, + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), sourceMaps: sourceMapDataList }; function isUniqueLocalName(name, container) { @@ -30429,6 +31377,8 @@ var ts; function createFileEmitter() { var writer = ts.createTextWriter(newLine); var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); + var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; var currentSourceFile; var currentText; var currentLineMap; @@ -30451,40 +31401,18 @@ var ts; var decorateEmitted; var paramEmitted; var awaiterEmitted; - var tempFlags; + var tempFlags = 0; var tempVariables; var tempParameters; var externalImports; var exportSpecifiers; var exportEquals; - var hasExportStars; - /** Write emitted output to disk */ - var writeEmittedFiles = writeJavaScriptFile; + var hasExportStarsToExportValues; var detachedCommentsInfo; - var writeComment = ts.writeCommentRange; - /** Emit a node */ - var emit = emitNodeWithCommentsAndWithoutSourcemap; - /** Called just before starting emit of a node */ - var emitStart = function (node) { }; - /** Called once the emit of the node is done */ - var emitEnd = function (node) { }; - /** Emit the text for the given token that comes after startPos - * This by default writes the text provided with the given tokenKind - * but if optional emitFn callback is provided the text is emitted using the callback instead of default text - * @param tokenKind the kind of the token to search and emit - * @param startPos the position in the source to start searching for the token - * @param emitFn if given will be invoked to emit the text instead of actual token emit */ - var emitToken = emitTokenText; - /** Called to before starting the lexical scopes as in function/class in the emitted code because of node - * @param scopeDeclaration node that starts the lexical scope - * @param scopeName Optional name of this scope instead of deducing one from the declaration node */ - var scopeEmitStart = function (scopeDeclaration, scopeName) { }; - /** Called after coming out of the scope */ - var scopeEmitEnd = function () { }; /** Sourcemap data that will get encoded */ var sourceMapData; - /** The root file passed to the emit function (if present) */ - var root; + /** Is the file being emitted into its own file */ + var isOwnFileEmit; /** If removeComments is true, no leading-comments needed to be emitted **/ var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; var moduleEmitDelegates = (_a = {}, @@ -30504,15 +31432,32 @@ var ts; _b ); return doEmit; - function doEmit(jsFilePath, rootFile) { + function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + generatedNameSet = {}; + nodeToGeneratedName = []; + isOwnFileEmit = !isBundledEmit; + // Emit helpers from all the files + if (isBundledEmit && modulekind) { + ts.forEach(sourceFiles, emitEmitHelpers); + } + // Do not call emit directly. It does not set the currentSourceFile. + ts.forEach(sourceFiles, emitSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# sourceMappingURL=" + sourceMappingURL); + } + writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM); // reset the state + sourceMap.reset(); writer.reset(); currentSourceFile = undefined; currentText = undefined; currentLineMap = undefined; exportFunctionForFile = undefined; - generatedNameSet = {}; - nodeToGeneratedName = []; + generatedNameSet = undefined; + nodeToGeneratedName = undefined; computedPropertyNamesToGeneratedNames = undefined; convertedLoopState = undefined; extendsEmitted = false; @@ -30525,32 +31470,12 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = undefined; + hasExportStarsToExportValues = undefined; detachedCommentsInfo = undefined; sourceMapData = undefined; isEs6Module = false; renamedDependencies = undefined; isCurrentFileExternalModule = false; - root = rootFile; - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - initializeEmitterWithSourceMaps(jsFilePath, root); - } - if (root) { - // Do not call emit directly. It does not set the currentSourceFile. - emitSourceFile(root); - } - else { - if (modulekind) { - ts.forEach(host.getSourceFiles(), emitEmitHelpers); - } - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if ((!isExternalModuleOrDeclarationFile(sourceFile)) || (modulekind && ts.isExternalModule(sourceFile))) { - emitSourceFile(sourceFile); - } - }); - } - writeLine(); - writeEmittedFiles(writer.getText(), jsFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM); } function emitSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -30561,7 +31486,8 @@ var ts; renamedDependencies = sourceFile.renamedDependencies; currentFileIdentifiers = sourceFile.identifiers; isCurrentFileExternalModule = ts.isExternalModule(sourceFile); - emit(sourceFile); + setSourceFile(sourceFile); + emitNodeWithCommentsAndWithoutSourcemap(sourceFile); } function isUniqueName(name) { return !resolver.hasGlobalName(name) && @@ -30630,17 +31556,17 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return makeUniqueName(node.text); - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: + case 220 /* ModuleDeclaration */: + case 219 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 222 /* ImportDeclaration */: - case 228 /* ExportDeclaration */: + case 224 /* ImportDeclaration */: + case 230 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 213 /* FunctionDeclaration */: - case 214 /* ClassDeclaration */: - case 227 /* ExportAssignment */: + case 215 /* FunctionDeclaration */: + case 216 /* ClassDeclaration */: + case 229 /* ExportAssignment */: return generateNameForExportDefault(); - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: return generateNameForClassExpression(); } } @@ -30648,338 +31574,15 @@ var ts; var id = ts.getNodeId(node); return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); } - function initializeEmitterWithSourceMaps(jsFilePath, root) { - var sourceMapDir; // The directory in which sourcemap will be - // Current source map file and its index in the sources list - var sourceMapSourceIndex = -1; - // Names and its index map - var sourceMapNameIndexMap = {}; - var sourceMapNameIndices = []; - function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; + /** Write emitted output to disk */ + function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark) { + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false); } - // Last recorded and encoded spans - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - var lastEncodedNameIndex = 0; - // Encoding for sourcemap span - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - // Line/Comma delimiters - if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { - // Emit comma to separate the entry - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - // Emit line delimiters - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - // 1. Relative Column 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - // 2. Relative sourceIndex - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - // 3. Relative sourceLine 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - // 4. Relative sourceColumn 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - // 5. Relative namePosition 0 based - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - function base64VLQFormatEncode(inValue) { - function base64FormatEncode(inValue) { - if (inValue < 64) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - // Add a new least significant bit that has the sign of the value. - // if negative number the least significant bit that gets added to the number has value 1 - // else least significant bit value that gets added is 0 - // eg. -1 changes to binary : 01 [1] => 3 - // +1 changes to binary : 01 [0] => 2 - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - // Encode 5 bits at a time starting from least significant bits - var encodedStr = ""; - do { - var currentDigit = inValue & 31; // 11111 - inValue = inValue >> 5; - if (inValue > 0) { - // There are still more digits to decode, set the msb (6th bit) - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; - } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); } - function recordSourceMapSpan(pos) { - var sourceLinePos = ts.computeLineAndCharacterOfPosition(currentLineMap, pos); - // Convert the location to be one-based. - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); - // If this location wasn't recorded or the location in source is going backwards, record the span - if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine !== emittedLine || - lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || - (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && - (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || - (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - // Encode the last recordedSpan before assigning new - encodeLastRecordedSourceMapSpan(); - // New span - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - nameIndex: getSourceMapNameIndex(), - sourceIndex: sourceMapSourceIndex - }; - } - else { - // Take the new pos instead since there is no change in emittedLine and column since last location - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - } - function recordEmitNodeStartSpan(node) { - // Get the token pos after skipping to the token (ignoring the leading trivia) - recordSourceMapSpan(ts.skipTrivia(currentText, node.pos)); - } - function recordEmitNodeEndSpan(node) { - recordSourceMapSpan(node.end); - } - function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentText, startPos); - recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); - recordSourceMapSpan(tokenEndPos); - return tokenEndPos; - } - function recordNewSourceFileStart(node) { - // Add the file to tsFilePaths - // If sourceroot option: Use the relative path corresponding to the common directory path - // otherwise source locations relative to map file location - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true)); - sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; - // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(node.fileName); - if (compilerOptions.inlineSources) { - if (!sourceMapData.sourceMapSourcesContent) { - sourceMapData.sourceMapSourcesContent = []; - } - sourceMapData.sourceMapSourcesContent.push(node.text); - } - } - function recordScopeNameOfNode(node, scopeName) { - function recordScopeNameIndex(scopeNameIndex) { - sourceMapNameIndices.push(scopeNameIndex); - } - function recordScopeNameStart(scopeName) { - var scopeNameIndex = -1; - if (scopeName) { - var parentIndex = getSourceMapNameIndex(); - if (parentIndex !== -1) { - // Child scopes are always shown with a dot (even if they have no name), - // unless it is a computed property. Then it is shown with brackets, - // but the brackets are included in the name. - var name_21 = node.name; - if (!name_21 || name_21.kind !== 136 /* ComputedPropertyName */) { - scopeName = "." + scopeName; - } - scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; - } - scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); - if (scopeNameIndex === undefined) { - scopeNameIndex = sourceMapData.sourceMapNames.length; - sourceMapData.sourceMapNames.push(scopeName); - sourceMapNameIndexMap[scopeName] = scopeNameIndex; - } - } - recordScopeNameIndex(scopeNameIndex); - } - if (scopeName) { - // The scope was already given a name use it - recordScopeNameStart(scopeName); - } - else if (node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */ || - node.kind === 143 /* MethodDeclaration */ || - node.kind === 142 /* MethodSignature */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */ || - node.kind === 218 /* ModuleDeclaration */ || - node.kind === 214 /* ClassDeclaration */ || - node.kind === 217 /* EnumDeclaration */) { - // Declaration and has associated name use it - if (node.name) { - var name_22 = node.name; - // For computed property names, the text will include the brackets - scopeName = name_22.kind === 136 /* ComputedPropertyName */ - ? ts.getTextOfNode(name_22) - : node.name.text; - } - recordScopeNameStart(scopeName); - } - else { - // Block just use the name from upper level scope - recordScopeNameIndex(getSourceMapNameIndex()); - } - } - function recordScopeNameEnd() { - sourceMapNameIndices.pop(); - } - ; - function writeCommentRangeWithMap(currentText, currentLineMap, writer, comment, newLine) { - recordSourceMapSpan(comment.pos); - ts.writeCommentRange(currentText, currentLineMap, writer, comment, newLine); - recordSourceMapSpan(comment.end); - } - function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) { - if (typeof JSON !== "undefined") { - var map_1 = { - version: version, - file: file, - sourceRoot: sourceRoot, - sources: sources, - names: names, - mappings: mappings - }; - if (sourcesContent !== undefined) { - map_1.sourcesContent = sourcesContent; - } - return JSON.stringify(map_1); - } - return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\" " + (sourcesContent !== undefined ? ",\"sourcesContent\":[" + serializeStringArray(sourcesContent) + "]" : "") + "}"; - function serializeStringArray(list) { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { - if (i) { - output += ","; - } - output += "\"" + ts.escapeString(list[i]) + "\""; - } - return output; - } - } - function writeJavaScriptAndSourceMapFile(emitOutput, jsFilePath, writeByteOrderMark) { - encodeLastRecordedSourceMapSpan(); - var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent); - sourceMapDataList.push(sourceMapData); - var sourceMapUrl; - if (compilerOptions.inlineSourceMap) { - // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.convertToBase64(sourceMapText); - sourceMapUrl = "//# sourceMappingURL=data:application/json;base64," + base64SourceMapText; - } - else { - // Write source map file - ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, /*writeByteOrderMark*/ false); - sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL; - } - // Write sourcemap url to the js file and write the js file - writeJavaScriptFile(emitOutput + sourceMapUrl, jsFilePath, writeByteOrderMark); - } - // Initialize source map data - var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)); - sourceMapData = { - sourceMapFilePath: jsFilePath + ".map", - jsSourceMappingURL: sourceMapJsFile + ".map", - sourceMapFile: sourceMapJsFile, - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapSourcesContent: undefined, - sourceMapDecodedMappings: [] - }; - // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the - // relative paths of the sources list in the sourcemap - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (root) { - // For modules or multiple emit files the mapRoot will have directory structure like the sources - // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - // The relative paths are relative to the common directory - sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), // get the relative sourceMapDir path based on jsFilePath - ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap - host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); - } - function emitNodeWithSourceMap(node) { - if (node) { - if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node); - } - if (node.kind !== 248 /* SourceFile */) { - recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node); - recordEmitNodeEndSpan(node); - } - else { - recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node); - } - } - } - function emitNodeWithCommentsAndWithSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - writeEmittedFiles = writeJavaScriptAndSourceMapFile; - emit = emitNodeWithCommentsAndWithSourcemap; - emitStart = recordEmitNodeStartSpan; - emitEnd = recordEmitNodeEndSpan; - emitToken = writeTextWithSpanRecord; - scopeEmitStart = recordScopeNameOfNode; - scopeEmitEnd = recordScopeNameEnd; - writeComment = writeCommentRangeWithMap; - } - function writeJavaScriptFile(emitOutput, jsFilePath, writeByteOrderMark) { - ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark); } // Create a temporary variable with a unique unused name. function createTempVariable(flags) { @@ -31011,7 +31614,15 @@ var ts; write(";"); } } - function emitTokenText(tokenKind, startPos, emitFn) { + /** Emit the text for the given token that comes after startPos + * This by default writes the text provided with the given tokenKind + * but if optional emitFn callback is provided the text is emitted using the callback instead of default text + * @param tokenKind the kind of the token to search and emit + * @param startPos the position in the source to start searching for the token + * @param emitFn if given will be invoked to emit the text instead of actual token emit */ + function emitToken(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentText, startPos); + emitPos(tokenStartPos); var tokenString = ts.tokenToString(tokenKind); if (emitFn) { emitFn(); @@ -31019,7 +31630,9 @@ var ts; else { write(tokenString); } - return startPos + tokenString.length; + var tokenEndPos = tokenStartPos + tokenString.length; + emitPos(tokenEndPos); + return tokenEndPos; } function emitOptional(prefix, node) { if (node) { @@ -31036,11 +31649,6 @@ var ts; write(")"); } } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { ts.Debug.assert(nodes.length > 0); increaseIndent(); @@ -31113,7 +31721,7 @@ var ts; } function emitCommaList(nodes) { if (nodes) { - emitList(nodes, 0, nodes.length, /*multiline*/ false, /*trailingComma*/ false); + emitList(nodes, 0, nodes.length, /*multiLine*/ false, /*trailingComma*/ false); } } function emitLines(nodes) { @@ -31228,10 +31836,10 @@ var ts; write("("); emit(tempVariable); // Now we emit the expressions - if (node.template.kind === 183 /* TemplateExpression */) { + if (node.template.kind === 185 /* TemplateExpression */) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 181 /* BinaryExpression */ + var needsParens = templateSpan.expression.kind === 183 /* BinaryExpression */ && templateSpan.expression.operatorToken.kind === 24 /* CommaToken */; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -31266,7 +31874,7 @@ var ts; // ("abc" + 1) << (2 + "") // rather than // "abc" + (1 << 2) + "" - var needsParens = templateSpan.expression.kind !== 172 /* ParenthesizedExpression */ + var needsParens = templateSpan.expression.kind !== 174 /* ParenthesizedExpression */ && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; if (i > 0 || headEmitted) { // If this is the first span and the head was not emitted, then this templateSpan's @@ -31308,11 +31916,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: return parent.expression === template; - case 170 /* TaggedTemplateExpression */: - case 172 /* ParenthesizedExpression */: + case 172 /* TaggedTemplateExpression */: + case 174 /* ParenthesizedExpression */: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; @@ -31333,7 +31941,7 @@ var ts; // TODO (drosen): Note that we need to account for the upcoming 'yield' and // spread ('...') unary operators that are anticipated for ES6. switch (expression.kind) { - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: switch (expression.operatorToken.kind) { case 37 /* AsteriskToken */: case 39 /* SlashToken */: @@ -31345,8 +31953,8 @@ var ts; default: return -1 /* LessThan */; } - case 184 /* YieldExpression */: - case 182 /* ConditionalExpression */: + case 186 /* YieldExpression */: + case 184 /* ConditionalExpression */: return -1 /* LessThan */; default: return 1 /* GreaterThan */; @@ -31374,13 +31982,13 @@ var ts; /// these emit into an object literal property name, we don't need to be worried /// about keywords, just non-identifier characters function emitAttributeName(name) { - if (/[A-Za-z_]+[\w*]/.test(name.text)) { - write("\""); + if (/^[A-Za-z_]\w*$/.test(name.text)) { emit(name); - write("\""); } else { + write("\""); emit(name); + write("\""); } } /// Emit an name/value pair for an attribute (e.g. "x: 3") @@ -31396,7 +32004,7 @@ var ts; } function emitJsxElement(openingNode, children) { var syntheticReactRef = ts.createSynthesizedNode(69 /* Identifier */); - syntheticReactRef.text = "React"; + syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; syntheticReactRef.parent = openingNode; // Call React.createElement(tag, ... emitLeadingComments(openingNode); @@ -31413,12 +32021,12 @@ var ts; // Either emit one big object literal (no spread attribs), or // a call to React.__spread var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 239 /* JsxSpreadAttribute */; })) { + if (ts.forEach(attrs, function (attr) { return attr.kind === 241 /* JsxSpreadAttribute */; })) { emitExpressionIdentifier(syntheticReactRef); write(".__spread("); var haveOpenedObjectLiteral = false; for (var i_1 = 0; i_1 < attrs.length; i_1++) { - if (attrs[i_1].kind === 239 /* JsxSpreadAttribute */) { + if (attrs[i_1].kind === 241 /* JsxSpreadAttribute */) { // If this is the first argument, we need to emit a {} as the first argument if (i_1 === 0) { write("{}, "); @@ -31433,7 +32041,7 @@ var ts; emit(attrs[i_1].expression); } else { - ts.Debug.assert(attrs[i_1].kind === 238 /* JsxAttribute */); + ts.Debug.assert(attrs[i_1].kind === 240 /* JsxAttribute */); if (haveOpenedObjectLiteral) { write(", "); } @@ -31467,11 +32075,11 @@ var ts; if (children) { for (var i = 0; i < children.length; i++) { // Don't emit empty expressions - if (children[i].kind === 240 /* JsxExpression */ && !(children[i].expression)) { + if (children[i].kind === 242 /* JsxExpression */ && !(children[i].expression)) { continue; } // Don't emit empty strings - if (children[i].kind === 236 /* JsxText */) { + if (children[i].kind === 238 /* JsxText */) { var text = getTextToEmit(children[i]); if (text !== undefined) { write(", \""); @@ -31489,11 +32097,11 @@ var ts; write(")"); // closes "React.createElement(" emitTrailingComments(openingNode); } - if (node.kind === 233 /* JsxElement */) { + if (node.kind === 235 /* JsxElement */) { emitJsxElement(node.openingElement, node.children); } else { - ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(node.kind === 236 /* JsxSelfClosingElement */); emitJsxElement(node); } } @@ -31515,11 +32123,11 @@ var ts; if (i > 0) { write(" "); } - if (attribs[i].kind === 239 /* JsxSpreadAttribute */) { + if (attribs[i].kind === 241 /* JsxSpreadAttribute */) { emitJsxSpreadAttribute(attribs[i]); } else { - ts.Debug.assert(attribs[i].kind === 238 /* JsxAttribute */); + ts.Debug.assert(attribs[i].kind === 240 /* JsxAttribute */); emitJsxAttribute(attribs[i]); } } @@ -31527,11 +32135,11 @@ var ts; function emitJsxOpeningOrSelfClosingElement(node) { write("<"); emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 234 /* JsxSelfClosingElement */)) { + if (node.attributes.length > 0 || (node.kind === 236 /* JsxSelfClosingElement */)) { write(" "); } emitAttributes(node.attributes); - if (node.kind === 234 /* JsxSelfClosingElement */) { + if (node.kind === 236 /* JsxSelfClosingElement */) { write("/>"); } else { @@ -31550,11 +32158,11 @@ var ts; } emitJsxClosingElement(node.closingElement); } - if (node.kind === 233 /* JsxElement */) { + if (node.kind === 235 /* JsxElement */) { emitJsxElement(node); } else { - ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(node.kind === 236 /* JsxSelfClosingElement */); emitJsxOpeningOrSelfClosingElement(node); } } @@ -31562,7 +32170,7 @@ var ts; // In a sense, it does not actually emit identifiers as much as it declares a name for a specific property. // For example, this is utilized when feeding in a result to Object.defineProperty. function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 163 /* BindingElement */); + ts.Debug.assert(node.kind !== 165 /* BindingElement */); if (node.kind === 9 /* StringLiteral */) { emitLiteral(node); } @@ -31610,59 +32218,60 @@ var ts; function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 164 /* ArrayLiteralExpression */: - case 189 /* AsExpression */: - case 181 /* BinaryExpression */: - case 168 /* CallExpression */: - case 241 /* CaseClause */: + case 166 /* ArrayLiteralExpression */: + case 191 /* AsExpression */: + case 183 /* BinaryExpression */: + case 170 /* CallExpression */: + case 243 /* CaseClause */: case 136 /* ComputedPropertyName */: - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: case 139 /* Decorator */: - case 175 /* DeleteExpression */: - case 197 /* DoStatement */: - case 167 /* ElementAccessExpression */: - case 227 /* ExportAssignment */: - case 195 /* ExpressionStatement */: - case 188 /* ExpressionWithTypeArguments */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 196 /* IfStatement */: - case 234 /* JsxSelfClosingElement */: - case 235 /* JsxOpeningElement */: - case 239 /* JsxSpreadAttribute */: - case 240 /* JsxExpression */: - case 169 /* NewExpression */: - case 172 /* ParenthesizedExpression */: - case 180 /* PostfixUnaryExpression */: - case 179 /* PrefixUnaryExpression */: - case 204 /* ReturnStatement */: - case 246 /* ShorthandPropertyAssignment */: - case 185 /* SpreadElementExpression */: - case 206 /* SwitchStatement */: - case 170 /* TaggedTemplateExpression */: - case 190 /* TemplateSpan */: - case 208 /* ThrowStatement */: - case 171 /* TypeAssertionExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 184 /* YieldExpression */: + case 177 /* DeleteExpression */: + case 199 /* DoStatement */: + case 169 /* ElementAccessExpression */: + case 229 /* ExportAssignment */: + case 197 /* ExpressionStatement */: + case 190 /* ExpressionWithTypeArguments */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 198 /* IfStatement */: + case 239 /* JsxClosingElement */: + case 236 /* JsxSelfClosingElement */: + case 237 /* JsxOpeningElement */: + case 241 /* JsxSpreadAttribute */: + case 242 /* JsxExpression */: + case 171 /* NewExpression */: + case 174 /* ParenthesizedExpression */: + case 182 /* PostfixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: + case 206 /* ReturnStatement */: + case 248 /* ShorthandPropertyAssignment */: + case 187 /* SpreadElementExpression */: + case 208 /* SwitchStatement */: + case 172 /* TaggedTemplateExpression */: + case 192 /* TemplateSpan */: + case 210 /* ThrowStatement */: + case 173 /* TypeAssertionExpression */: + case 178 /* TypeOfExpression */: + case 179 /* VoidExpression */: + case 200 /* WhileStatement */: + case 207 /* WithStatement */: + case 186 /* YieldExpression */: return true; - case 163 /* BindingElement */: - case 247 /* EnumMember */: + case 165 /* BindingElement */: + case 249 /* EnumMember */: case 138 /* Parameter */: - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: case 141 /* PropertyDeclaration */: - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: return parent.initializer === node; - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: return parent.expression === node; - case 174 /* ArrowFunction */: - case 173 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 175 /* FunctionExpression */: return parent.body === node; - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return parent.moduleReference === node; case 135 /* QualifiedName */: return parent.left === node; @@ -31676,7 +32285,7 @@ var ts; } var container = resolver.getReferencedExportContainer(node); if (container) { - if (container.kind === 248 /* SourceFile */) { + if (container.kind === 250 /* SourceFile */) { // Identifier references module export if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) { write("exports."); @@ -31692,17 +32301,17 @@ var ts; if (modulekind !== 5 /* ES6 */) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { - if (declaration.kind === 223 /* ImportClause */) { + if (declaration.kind === 225 /* ImportClause */) { // Identifier references default import write(getGeneratedNameForNode(declaration.parent)); write(languageVersion === 0 /* ES3 */ ? "[\"default\"]" : ".default"); return; } - else if (declaration.kind === 226 /* ImportSpecifier */) { + else if (declaration.kind === 228 /* ImportSpecifier */) { // Identifier references named import write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_23 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_23); + var name_21 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_21); if (languageVersion === 0 /* ES3 */ && identifier === "default") { write("[\"default\"]"); } @@ -31733,10 +32342,10 @@ var ts; if (languageVersion < 2 /* ES6 */) { var parent_6 = node.parent; switch (parent_6.kind) { - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 211 /* VariableDeclaration */: + case 165 /* BindingElement */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 213 /* VariableDeclaration */: return parent_6.name === node && resolver.isNestedRedeclaration(parent_6); } } @@ -31746,8 +32355,8 @@ var ts; if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { // in converted loop body arguments cannot be used directly. - var name_24 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_24); + var name_22 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_22); return; } } @@ -31771,6 +32380,9 @@ var ts; if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { write("_this"); } + else if (convertedLoopState) { + write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); + } else { write("this"); } @@ -31844,10 +32456,10 @@ var ts; } } function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 181 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { + if (node.parent.kind === 183 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { return true; } - else if (node.parent.kind === 182 /* ConditionalExpression */ && node.parent.condition === node) { + else if (node.parent.kind === 184 /* ConditionalExpression */ && node.parent.condition === node) { return true; } return false; @@ -31855,11 +32467,11 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 69 /* Identifier */: - case 164 /* ArrayLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 172 /* ParenthesizedExpression */: + case 166 /* ArrayLiteralExpression */: + case 168 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: + case 170 /* CallExpression */: + case 174 /* ParenthesizedExpression */: // This list is not exhaustive and only includes those cases that are relevant // to the check in emitArrayLiteral. More cases can be added as needed. return false; @@ -31879,17 +32491,17 @@ var ts; write(", "); } var e = elements[pos]; - if (e.kind === 185 /* SpreadElementExpression */) { + if (e.kind === 187 /* SpreadElementExpression */) { e = e.expression; emitParenthesizedIf(e, /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164 /* ArrayLiteralExpression */) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 166 /* ArrayLiteralExpression */) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 185 /* SpreadElementExpression */) { + while (i < length && elements[i].kind !== 187 /* SpreadElementExpression */) { i++; } write("["); @@ -31912,7 +32524,7 @@ var ts; } } function isSpreadElementExpression(node) { - return node.kind === 185 /* SpreadElementExpression */; + return node.kind === 187 /* SpreadElementExpression */; } function emitArrayLiteral(node) { var elements = node.elements; @@ -31921,7 +32533,7 @@ var ts; } else if (languageVersion >= 2 /* ES6 */ || !ts.forEach(elements, isSpreadElementExpression)) { write("["); - emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces:*/ false); + emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces*/ false); write("]"); } else { @@ -31941,7 +32553,7 @@ var ts; // then try to preserve the original shape of the object literal. // Otherwise just try to preserve the formatting. if (numElements === properties.length) { - emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= 1 /* ES5 */, /* spacesBetweenBraces */ true); + emitLinePreservingList(node, properties, /*allowTrailingComma*/ languageVersion >= 1 /* ES5 */, /*spacesBetweenBraces*/ true); } else { var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; @@ -32034,10 +32646,10 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 245 /* PropertyAssignment */) { + if (property.kind === 247 /* PropertyAssignment */) { emit(property.initializer); } - else if (property.kind === 246 /* ShorthandPropertyAssignment */) { + else if (property.kind === 248 /* ShorthandPropertyAssignment */) { emitExpressionIdentifier(property.name); } else if (property.kind === 143 /* MethodDeclaration */) { @@ -32090,21 +32702,21 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(181 /* BinaryExpression */, startsOnNewLine); + var result = ts.createSynthesizedNode(183 /* BinaryExpression */, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(166 /* PropertyAccessExpression */); + var result = ts.createSynthesizedNode(168 /* PropertyAccessExpression */); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(21 /* DotToken */); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(167 /* ElementAccessExpression */); + var result = ts.createSynthesizedNode(169 /* ElementAccessExpression */); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; @@ -32112,7 +32724,7 @@ var ts; function parenthesizeForAccess(expr) { // When diagnosing whether the expression needs parentheses, the decision should be based // on the innermost expression in a chain of nested type assertions. - while (expr.kind === 171 /* TypeAssertionExpression */ || expr.kind === 189 /* AsExpression */) { + while (expr.kind === 173 /* TypeAssertionExpression */ || expr.kind === 191 /* AsExpression */) { expr = expr.expression; } // isLeftHandSideExpression is almost the correct criterion for when it is not necessary @@ -32124,11 +32736,11 @@ var ts; // 1.x -> not the same as (1).x // if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 169 /* NewExpression */ && + expr.kind !== 171 /* NewExpression */ && expr.kind !== 8 /* NumericLiteral */) { return expr; } - var node = ts.createSynthesizedNode(172 /* ParenthesizedExpression */); + var node = ts.createSynthesizedNode(174 /* ParenthesizedExpression */); node.expression = expr; return node; } @@ -32163,7 +32775,7 @@ var ts; // Return true if identifier resolves to an exported member of a namespace function isNamespaceExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 248 /* SourceFile */; + return container && container.kind !== 250 /* SourceFile */; } function emitShorthandPropertyAssignment(node) { // The name property of a short-hand property assignment is considered an expression position, so here @@ -32193,7 +32805,7 @@ var ts; if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 166 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 168 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -32204,7 +32816,7 @@ var ts; if (compilerOptions.isolatedModules) { return undefined; } - return node.kind === 166 /* PropertyAccessExpression */ || node.kind === 167 /* ElementAccessExpression */ + return node.kind === 168 /* PropertyAccessExpression */ || node.kind === 169 /* ElementAccessExpression */ ? resolver.getConstantValue(node) : undefined; } @@ -32296,6 +32908,9 @@ var ts; case 135 /* QualifiedName */: emitQualifiedNameAsExpression(node, useFallback); break; + default: + emitNodeWithoutSourceMap(node); + break; } } function emitIndexedAccess(node) { @@ -32308,10 +32923,10 @@ var ts; write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 185 /* SpreadElementExpression */; }); + return ts.forEach(elements, function (e) { return e.kind === 187 /* SpreadElementExpression */; }); } function skipParentheses(node) { - while (node.kind === 172 /* ParenthesizedExpression */ || node.kind === 171 /* TypeAssertionExpression */ || node.kind === 189 /* AsExpression */) { + while (node.kind === 174 /* ParenthesizedExpression */ || node.kind === 173 /* TypeAssertionExpression */ || node.kind === 191 /* AsExpression */) { node = node.expression; } return node; @@ -32332,13 +32947,13 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 166 /* PropertyAccessExpression */) { + if (expr.kind === 168 /* PropertyAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 167 /* ElementAccessExpression */) { + else if (expr.kind === 169 /* ElementAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("["); @@ -32383,7 +32998,7 @@ var ts; } else { emit(node.expression); - superCall = node.expression.kind === 166 /* PropertyAccessExpression */ && node.expression.expression.kind === 95 /* SuperKeyword */; + superCall = node.expression.kind === 168 /* PropertyAccessExpression */ && node.expression.expression.kind === 95 /* SuperKeyword */; } if (superCall && languageVersion < 2 /* ES6 */) { write(".call("); @@ -32425,7 +33040,7 @@ var ts; write(".bind.apply("); emit(target); write(", [void 0].concat("); - emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiline*/ false, /*trailingComma*/ false, /*useConcat*/ false); + emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ false); write(")))"); write("()"); } @@ -32452,12 +33067,12 @@ var ts; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. - if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 174 /* ArrowFunction */) { - if (node.expression.kind === 171 /* TypeAssertionExpression */ || node.expression.kind === 189 /* AsExpression */) { + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 176 /* ArrowFunction */) { + if (node.expression.kind === 173 /* TypeAssertionExpression */ || node.expression.kind === 191 /* AsExpression */) { var operand = node.expression.expression; // Make sure we consider all nested cast expressions, e.g.: // (-A).x; - while (operand.kind === 171 /* TypeAssertionExpression */ || operand.kind === 189 /* AsExpression */) { + while (operand.kind === 173 /* TypeAssertionExpression */ || operand.kind === 191 /* AsExpression */) { operand = operand.expression; } // We have an expression of the form: (SubExpr) @@ -32468,15 +33083,15 @@ var ts; // (typeof A).toString() should be emitted as (typeof A).toString() and not typeof A.toString() // new (A()) should be emitted as new (A()) and not new A() // (function foo() { })() should be emitted as an IIF (function foo(){})() and not declaration function foo(){} () - if (operand.kind !== 179 /* PrefixUnaryExpression */ && - operand.kind !== 177 /* VoidExpression */ && - operand.kind !== 176 /* TypeOfExpression */ && - operand.kind !== 175 /* DeleteExpression */ && - operand.kind !== 180 /* PostfixUnaryExpression */ && - operand.kind !== 169 /* NewExpression */ && - !(operand.kind === 168 /* CallExpression */ && node.parent.kind === 169 /* NewExpression */) && - !(operand.kind === 173 /* FunctionExpression */ && node.parent.kind === 168 /* CallExpression */) && - !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 166 /* PropertyAccessExpression */)) { + if (operand.kind !== 181 /* PrefixUnaryExpression */ && + operand.kind !== 179 /* VoidExpression */ && + operand.kind !== 178 /* TypeOfExpression */ && + operand.kind !== 177 /* DeleteExpression */ && + operand.kind !== 182 /* PostfixUnaryExpression */ && + operand.kind !== 171 /* NewExpression */ && + !(operand.kind === 170 /* CallExpression */ && node.parent.kind === 171 /* NewExpression */) && + !(operand.kind === 175 /* FunctionExpression */ && node.parent.kind === 170 /* CallExpression */) && + !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 168 /* PropertyAccessExpression */)) { emit(operand); return; } @@ -32505,14 +33120,15 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 211 /* VariableDeclaration */ || node.parent.kind === 163 /* BindingElement */); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 213 /* VariableDeclaration */ || node.parent.kind === 165 /* BindingElement */); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, /*isExported*/ true); } function emitPrefixUnaryExpression(node) { - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); + var exportChanged = (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) && + isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); if (exportChanged) { // emit // ++x @@ -32535,7 +33151,7 @@ var ts; // the resulting expression a prefix increment operation. And in the second, it will make the resulting // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. - if (node.operand.kind === 179 /* PrefixUnaryExpression */) { + if (node.operand.kind === 181 /* PrefixUnaryExpression */) { var operand = node.operand; if (node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) { write(" "); @@ -32591,10 +33207,10 @@ var ts; } var current = node; while (current) { - if (current.kind === 248 /* SourceFile */) { + if (current.kind === 250 /* SourceFile */) { return !isExported || ((ts.getCombinedNodeFlags(node) & 2 /* Export */) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 219 /* ModuleBlock */) { + else if (ts.isFunctionLike(current) || current.kind === 221 /* ModuleBlock */) { return false; } else { @@ -32614,8 +33230,8 @@ var ts; if (ts.isElementAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(167 /* ElementAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false); + synthesizedLHS = ts.createSynthesizedNode(169 /* ElementAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; if (leftHandSideExpression.argumentExpression.kind !== 8 /* NumericLiteral */ && leftHandSideExpression.argumentExpression.kind !== 9 /* StringLiteral */) { @@ -32631,8 +33247,8 @@ var ts; else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(166 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false); + synthesizedLHS = ts.createSynthesizedNode(168 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; @@ -32659,8 +33275,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 56 /* EqualsToken */ && - (node.left.kind === 165 /* ObjectLiteralExpression */ || node.left.kind === 164 /* ArrayLiteralExpression */)) { - emitDestructuring(node, node.parent.kind === 195 /* ExpressionStatement */); + (node.left.kind === 167 /* ObjectLiteralExpression */ || node.left.kind === 166 /* ArrayLiteralExpression */)) { + emitDestructuring(node, node.parent.kind === 197 /* ExpressionStatement */); } else { var exportChanged = node.operatorToken.kind >= 56 /* FirstAssignment */ && @@ -32725,7 +33341,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 192 /* Block */) { + if (node && node.kind === 194 /* Block */) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -32739,22 +33355,20 @@ var ts; } emitToken(15 /* OpenBraceToken */, node.pos); increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 219 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 218 /* ModuleDeclaration */); + if (node.kind === 221 /* ModuleBlock */) { + ts.Debug.assert(node.parent.kind === 220 /* ModuleDeclaration */); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 219 /* ModuleBlock */) { + if (node.kind === 221 /* ModuleBlock */) { emitTempDeclarations(/*newLine*/ true); } decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.statements.end); - scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 192 /* Block */) { + if (node.kind === 194 /* Block */) { write(" "); emit(node); } @@ -32766,7 +33380,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 174 /* ArrowFunction */); + emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 176 /* ArrowFunction */); write(";"); } function emitIfStatement(node) { @@ -32779,7 +33393,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(80 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 196 /* IfStatement */) { + if (node.elseStatement.kind === 198 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -32794,12 +33408,12 @@ var ts; function emitDoStatementWorker(node, loop) { write("do"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } - if (node.statement.kind === 192 /* Block */) { + if (node.statement.kind === 194 /* Block */) { write(" "); } else { @@ -32817,10 +33431,10 @@ var ts; emit(node.expression); write(")"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } /** @@ -32834,7 +33448,7 @@ var ts; return false; } if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 24576 /* BlockScoped */) === 0) { - // we are inside a converted loop - this can only happen in downlevel scenarios + // we are inside a converted loop - this can only happen in downlevel scenarios // record names for all variable declarations for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { var varDecl = _b[_a]; @@ -32898,7 +33512,7 @@ var ts; } else { var loop = convertLoopBody(node); - if (node.parent.kind === 207 /* LabeledStatement */) { + if (node.parent.kind === 209 /* LabeledStatement */) { // if parent of the loop was labeled statement - attach the label to loop skipping converted loop body emitLabelAndColon(node.parent); } @@ -32909,10 +33523,10 @@ var ts; var functionName = makeUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + if (node.initializer.kind === 214 /* VariableDeclarationList */) { loopInitializer = node.initializer; } break; @@ -32926,7 +33540,7 @@ var ts; collectNames(varDeclaration.name); } } - var bodyIsBlock = node.statement.kind === 192 /* Block */; + var bodyIsBlock = node.statement.kind === 194 /* Block */; var paramList = loopParameters ? loopParameters.join(", ") : ""; writeLine(); write("var " + functionName + " = function(" + paramList + ")"); @@ -32945,6 +33559,11 @@ var ts; // use the same name in all nested loops convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; } + if (convertedOuterLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.thisName = convertedOuterLoopState.thisName; + } if (convertedOuterLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop @@ -32971,6 +33590,21 @@ var ts; writeLine(); } } + if (convertedLoopState.thisName) { + // if alias for this is set + if (convertedOuterLoopState) { + // pass it to outer converted loop + convertedOuterLoopState.thisName = convertedLoopState.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + write("var " + convertedLoopState.thisName + " = this;"); + writeLine(); + } + } if (convertedLoopState.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later if (convertedOuterLoopState) { @@ -33027,7 +33661,7 @@ var ts; if (emitAsEmbeddedStatement) { emitEmbeddedStatement(node.statement); } - else if (node.statement.kind === 192 /* Block */) { + else if (node.statement.kind === 194 /* Block */) { emitLines(node.statement.statements); } else { @@ -33097,8 +33731,8 @@ var ts; } write("switch(" + loopResultVariable + ") {"); increaseIndent(); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /* isBreak */ true, loopResultVariable, outerLoop); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /* isBreak */ false, loopResultVariable, outerLoop); + emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /*isBreak*/ true, loopResultVariable, outerLoop); + emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /*isBreak*/ false, loopResultVariable, outerLoop); decreaseIndent(); writeLine(); write("}"); @@ -33113,7 +33747,7 @@ var ts; write("case \"" + labelMarker + "\": "); // if there are no outer converted loop or outer label in question is located inside outer converted loop // then emit labeled break\continue - // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { if (isBreak) { write("break "); @@ -33137,7 +33771,7 @@ var ts; var endPos = emitToken(86 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 214 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); if (startIsEmitted) { @@ -33156,14 +33790,14 @@ var ts; emitOptional(" ", node.incrementor); write(")"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 /* ES6 */ && node.kind === 201 /* ForOfStatement */) { + if (languageVersion < 2 /* ES6 */ && node.kind === 203 /* ForOfStatement */) { emitLoop(node, emitDownLevelForOfStatementWorker); } else { @@ -33174,7 +33808,7 @@ var ts; var endPos = emitToken(86 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 214 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); @@ -33184,7 +33818,7 @@ var ts; else { emit(node.initializer); } - if (node.kind === 200 /* ForInStatement */) { + if (node.kind === 202 /* ForInStatement */) { write(" in "); } else { @@ -33193,15 +33827,12 @@ var ts; emit(node.expression); emitToken(18 /* CloseParenToken */, node.expression.end); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } - function emitDownLevelForOfStatement(node) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } function emitDownLevelForOfStatementWorker(node, loop) { // The following ES6 code: // @@ -33277,7 +33908,7 @@ var ts; // let v = _a[_i]; var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 214 /* VariableDeclarationList */) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -33307,7 +33938,7 @@ var ts; // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. var assignmentExpression = createBinaryExpression(node.initializer, 56 /* EqualsToken */, rhsIterationValue, /*startsOnNewLine*/ false); - if (node.initializer.kind === 164 /* ArrayLiteralExpression */ || node.initializer.kind === 165 /* ObjectLiteralExpression */) { + if (node.initializer.kind === 166 /* ArrayLiteralExpression */ || node.initializer.kind === 167 /* ObjectLiteralExpression */) { // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash. emitDestructuring(assignmentExpression, /*isAssignmentExpressionStatement*/ true, /*value*/ undefined); @@ -33320,10 +33951,10 @@ var ts; write(";"); if (loop) { writeLine(); - emitConvertedLoopCall(loop, /* emitAsBlock */ false); + emitConvertedLoopCall(loop, /*emitAsBlock*/ false); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ false); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ false); } writeLine(); decreaseIndent(); @@ -33335,12 +33966,12 @@ var ts; // it is possible if either // - break\continue is statement labeled and label is located inside the converted loop // - break\continue is non-labeled and located in non-converted loop\switch statement - var jump = node.kind === 203 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 205 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { if (!node.label) { - if (node.kind === 203 /* BreakStatement */) { + if (node.kind === 205 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; write("return \"break\";"); } @@ -33351,20 +33982,20 @@ var ts; } else { var labelMarker; - if (node.kind === 203 /* BreakStatement */) { + if (node.kind === 205 /* BreakStatement */) { labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, /* isBreak */ true, node.label.text, labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); } else { labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, /* isBreak */ false, node.label.text, labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); } write("return \"" + labelMarker + "\";"); } return; } } - emitToken(node.kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); + emitToken(node.kind === 205 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); emitOptional(" ", node.label); write(";"); } @@ -33430,7 +34061,7 @@ var ts; ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 241 /* CaseClause */) { + if (node.kind === 243 /* CaseClause */) { write("case "); emit(node.expression); write(":"); @@ -33499,7 +34130,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 218 /* ModuleDeclaration */); + } while (node && node.kind !== 220 /* ModuleDeclaration */); return node; } function emitContainingModuleName(node) { @@ -33524,22 +34155,22 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(8 /* NumericLiteral */); zero.text = "0"; - var result = ts.createSynthesizedNode(177 /* VoidExpression */); + var result = ts.createSynthesizedNode(179 /* VoidExpression */); result.expression = zero; return result; } function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 248 /* SourceFile */) { - ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 227 /* ExportAssignment */); + if (node.parent.kind === 250 /* SourceFile */) { + ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 229 /* ExportAssignment */); // only allow export default at a source file level if (modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */) { if (!isEs6Module) { - if (languageVersion === 1 /* ES5 */) { + if (languageVersion !== 0 /* ES3 */) { // default value of configurable, enumerable, writable are `false`. write("Object.defineProperty(exports, \"__esModule\", { value: true });"); writeLine(); } - else if (languageVersion === 0 /* ES3 */) { + else { write("exports.__esModule = true;"); writeLine(); } @@ -33636,7 +34267,7 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(name); write("\", "); } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 /* VariableDeclaration */ || name.parent.kind === 163 /* BindingElement */); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 213 /* VariableDeclaration */ || name.parent.kind === 165 /* BindingElement */); if (isVariableDeclarationOrBindingElement) { emitModuleMemberName(name.parent); } @@ -33670,7 +34301,7 @@ var ts; // Also temporary variables should be explicitly allocated for source level declarations when module target is system // because actual variable declarations are hoisted var canDefineTempVariablesInPlace = false; - if (root.kind === 211 /* VariableDeclaration */) { + if (root.kind === 213 /* VariableDeclaration */) { var isExported = ts.getCombinedNodeFlags(root) & 2 /* Export */; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; @@ -33678,7 +34309,7 @@ var ts; else if (root.kind === 138 /* Parameter */) { canDefineTempVariablesInPlace = true; } - if (root.kind === 181 /* BinaryExpression */) { + if (root.kind === 183 /* BinaryExpression */) { emitAssignmentExpression(root); } else { @@ -33707,14 +34338,14 @@ var ts; // we need to generate a temporary variable value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); // Return the expression 'value === void 0 ? defaultValue : value' - var equals = ts.createSynthesizedNode(181 /* BinaryExpression */); + var equals = ts.createSynthesizedNode(183 /* BinaryExpression */); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(32 /* EqualsEqualsEqualsToken */); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(182 /* ConditionalExpression */); + var cond = ts.createSynthesizedNode(184 /* ConditionalExpression */); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(53 /* QuestionToken */); cond.whenTrue = whenTrue; @@ -33731,7 +34362,7 @@ var ts; var index; var nameIsComputed = propName.kind === 136 /* ComputedPropertyName */; if (nameIsComputed) { - index = ensureIdentifier(propName.expression, /* reuseIdentifierExpression */ false); + index = ensureIdentifier(propName.expression, /*reuseIdentifierExpressions*/ false); } else { // We create a synthetic copy of the identifier in order to avoid the rewriting that might @@ -33744,7 +34375,7 @@ var ts; : createElementAccessExpression(object, index); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(168 /* CallExpression */); + var call = ts.createSynthesizedNode(170 /* CallExpression */); var sliceIdentifier = ts.createSynthesizedNode(69 /* Identifier */); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -33761,9 +34392,9 @@ var ts; } for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { var p = properties_5[_a]; - if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { + if (p.kind === 247 /* PropertyAssignment */ || p.kind === 248 /* ShorthandPropertyAssignment */) { var propName = p.name; - var target_1 = p.kind === 246 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; + var target_1 = p.kind === 248 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName)); } } @@ -33777,8 +34408,8 @@ var ts; } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187 /* OmittedExpression */) { - if (e.kind !== 185 /* SpreadElementExpression */) { + if (e.kind !== 189 /* OmittedExpression */) { + if (e.kind !== 187 /* SpreadElementExpression */) { emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); } else if (i === elements.length - 1) { @@ -33788,20 +34419,20 @@ var ts; } } function emitDestructuringAssignment(target, value) { - if (target.kind === 246 /* ShorthandPropertyAssignment */) { + if (target.kind === 248 /* ShorthandPropertyAssignment */) { if (target.objectAssignmentInitializer) { value = createDefaultValueCheck(value, target.objectAssignmentInitializer); } target = target.name; } - else if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + else if (target.kind === 183 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { value = createDefaultValueCheck(value, target.right); target = target.left; } - if (target.kind === 165 /* ObjectLiteralExpression */) { + if (target.kind === 167 /* ObjectLiteralExpression */) { emitObjectLiteralAssignment(target, value); } - else if (target.kind === 164 /* ArrayLiteralExpression */) { + else if (target.kind === 166 /* ArrayLiteralExpression */) { emitArrayLiteralAssignment(target, value); } else { @@ -33819,14 +34450,14 @@ var ts; emitDestructuringAssignment(target, value); } else { - if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + if (root.parent.kind !== 174 /* ParenthesizedExpression */) { write("("); } value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); emitDestructuringAssignment(target, value); write(", "); emit(value); - if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + if (root.parent.kind !== 174 /* ParenthesizedExpression */) { write(")"); } } @@ -33853,12 +34484,12 @@ var ts; } for (var i = 0; i < numElements; i++) { var element = elements[i]; - if (pattern.kind === 161 /* ObjectBindingPattern */) { + if (pattern.kind === 163 /* ObjectBindingPattern */) { // Rewrite element to a declaration with an initializer that fetches property var propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } - else if (element.kind !== 187 /* OmittedExpression */) { + else if (element.kind !== 189 /* OmittedExpression */) { if (!element.dotDotDotToken) { // Rewrite element to a declaration that accesses array element at index i emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); @@ -33898,8 +34529,8 @@ var ts; (getCombinedFlagsForIdentifier(node.name) & 8192 /* Let */); // NOTE: default initialization should not be added to let bindings in for-in\for-of statements if (isLetDefinedInLoop && - node.parent.parent.kind !== 200 /* ForInStatement */ && - node.parent.parent.kind !== 201 /* ForOfStatement */) { + node.parent.parent.kind !== 202 /* ForInStatement */ && + node.parent.parent.kind !== 203 /* ForOfStatement */) { initializer = createVoidZero(); } } @@ -33917,7 +34548,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 187 /* OmittedExpression */) { + if (node.kind === 189 /* OmittedExpression */) { return; } var name = node.name; @@ -33929,7 +34560,7 @@ var ts; } } function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 211 /* VariableDeclaration */ && node.parent.kind !== 163 /* BindingElement */)) { + if (!node.parent || (node.parent.kind !== 213 /* VariableDeclaration */ && node.parent.kind !== 165 /* BindingElement */)) { return 0; } return ts.getCombinedNodeFlags(node.parent); @@ -33937,7 +34568,7 @@ var ts; function isES6ExportedDeclaration(node) { return !!(node.flags & 2 /* Export */) && modulekind === 5 /* ES6 */ && - node.parent.kind === 248 /* SourceFile */; + node.parent.kind === 250 /* SourceFile */; } function emitVariableStatement(node) { var startIsEmitted = false; @@ -33988,12 +34619,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2 /* ES6 */) { if (ts.isBindingPattern(node.name)) { - var name_25 = createTempVariable(0 /* Auto */); + var name_23 = createTempVariable(0 /* Auto */); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_25); - emit(name_25); + tempParameters.push(name_23); + emit(name_23); } else { emit(node.name); @@ -34103,7 +34734,7 @@ var ts; emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 174 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; + return node.kind === 176 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; } function emitDeclarationName(node) { if (node.name) { @@ -34114,13 +34745,13 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 173 /* FunctionExpression */) { + if (node.kind === 175 /* FunctionExpression */) { // Emit name if one is present return !!node.name; } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 215 /* FunctionDeclaration */) { // Emit name if one is present, or emit generated name in down-level case (for export default case) - return !!node.name || languageVersion < 2 /* ES6 */; + return !!node.name || modulekind !== 5 /* ES6 */; } } function emitFunctionDeclaration(node) { @@ -34129,20 +34760,29 @@ var ts; } // TODO (yuisu) : we should not have special cases to condition emitting comments // but have one place to fix check for these conditions. - if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */ && - node.parent && node.parent.kind !== 245 /* PropertyAssignment */ && - node.parent.kind !== 168 /* CallExpression */) { - // 1. Methods will emit the comments as part of emitting method declaration + var kind = node.kind, parent = node.parent; + if (kind !== 143 /* MethodDeclaration */ && + kind !== 142 /* MethodSignature */ && + parent && + parent.kind !== 247 /* PropertyAssignment */ && + parent.kind !== 170 /* CallExpression */ && + parent.kind !== 166 /* ArrayLiteralExpression */) { + // 1. Methods will emit comments at their assignment declaration sites. + // // 2. If the function is a property of object literal, emitting leading-comments - // is done by emitNodeWithoutSourceMap which then call this function. - // In particular, we would like to avoid emit comments twice in following case: - // For example: + // is done by emitNodeWithoutSourceMap which then call this function. + // In particular, we would like to avoid emit comments twice in following case: + // // var obj = { // id: // /*comment*/ () => void // } + // // 3. If the function is an argument in call expression, emitting of comments will be - // taken care of in emit list of arguments inside of emitCallexpression + // taken care of in emit list of arguments inside of 'emitCallExpression'. + // + // 4. If the function is in an array literal, 'emitLinePreservingList' will take care + // of leading comments. emitLeadingComments(node); } emitStart(node); @@ -34165,11 +34805,11 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (modulekind !== 5 /* ES6 */ && node.kind === 213 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) { + if (modulekind !== 5 /* ES6 */ && kind === 215 /* FunctionDeclaration */ && parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } emitEnd(node); - if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) { + if (kind !== 143 /* MethodDeclaration */ && kind !== 142 /* MethodSignature */) { emitTrailingComments(node); } } @@ -34202,7 +34842,7 @@ var ts; } function emitAsyncFunctionBodyForES6(node) { var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 174 /* ArrowFunction */; + var isArrowFunction = node.kind === 176 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -34285,17 +34925,16 @@ var ts; } write(" __awaiter(this"); if (hasLexicalArguments) { - write(", arguments"); + write(", arguments, "); } else { - write(", void 0"); + write(", void 0, "); } if (promiseConstructor) { - write(", "); - emitNodeWithoutSourceMap(promiseConstructor); + emitEntityNameAsExpression(promiseConstructor, /*useFallback*/ false); } else { - write(", Promise"); + write("Promise"); } // Emit the call to __awaiter. if (hasLexicalArguments) { @@ -34322,7 +34961,7 @@ var ts; write(" { }"); } else { - if (node.body.kind === 192 /* Block */) { + if (node.body.kind === 194 /* Block */) { emitBlockFunctionBody(node, node.body); } else { @@ -34348,7 +34987,7 @@ var ts; emitSignatureParameters(node); } var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync && languageVersion === 2 /* ES6 */) { + if (isAsync) { emitAsyncFunctionBodyForES6(node); } else { @@ -34381,14 +35020,13 @@ var ts; write(" "); // Unwrap all type assertions. var current = body; - while (current.kind === 171 /* TypeAssertionExpression */) { + while (current.kind === 173 /* TypeAssertionExpression */) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 165 /* ObjectLiteralExpression */); + emitParenthesizedIf(body, current.kind === 167 /* ObjectLiteralExpression */); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); emitDetachedCommentsAndUpdateCommentsInfo(node.body); @@ -34411,8 +35049,10 @@ var ts; increaseIndent(); writeLine(); emitLeadingComments(node.body); + emitStart(body); write("return "); emit(body); + emitEnd(body); write(";"); emitTrailingComments(node.body); emitTempDeclarations(/*newLine*/ true); @@ -34422,11 +35062,9 @@ var ts; emitStart(node.body); write("}"); emitEnd(node.body); - scopeEmitEnd(); } function emitBlockFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); emitDetachedCommentsAndUpdateCommentsInfo(body.statements); @@ -34455,14 +35093,13 @@ var ts; decreaseIndent(); } emitToken(16 /* CloseBraceToken */, body.statements.end); - scopeEmitEnd(); } function findInitialSuperCall(ctor) { if (ctor.body) { var statement = ctor.body.statements[0]; - if (statement && statement.kind === 195 /* ExpressionStatement */) { + if (statement && statement.kind === 197 /* ExpressionStatement */) { var expr = statement.expression; - if (expr && expr.kind === 168 /* CallExpression */) { + if (expr && expr.kind === 170 /* CallExpression */) { var func = expr.expression; if (func && func.kind === 95 /* SuperKeyword */) { return statement; @@ -34548,7 +35185,7 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 191 /* SemicolonClassElement */) { + if (member.kind === 193 /* SemicolonClassElement */) { writeLine(); write(";"); } @@ -34645,7 +35282,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 191 /* SemicolonClassElement */) { + else if (member.kind === 193 /* SemicolonClassElement */) { writeLine(); write(";"); } @@ -34719,7 +35356,6 @@ var ts; } var startIndex = 0; write(" {"); - scopeEmitStart(node, "constructor"); increaseIndent(); if (ctor) { // Emit all the directive prologues (like "use strict"). These have to come before @@ -34754,7 +35390,7 @@ var ts; emitEnd(baseTypeElement); } } - emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false)); + emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ false)); if (ctor) { var statements = ctor.body.statements; if (superCall) { @@ -34769,7 +35405,6 @@ var ts; } decreaseIndent(); emitToken(16 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); emitEnd(ctor || node); if (ctor) { emitTrailingComments(ctor); @@ -34794,7 +35429,7 @@ var ts; } function emitClassLikeDeclarationForES6AndHigher(node) { var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { if (thisNodeIsDecorated) { // To preserve the correct runtime semantics when decorators are applied to the class, // the emit needs to follow one of the following rules: @@ -34870,8 +35505,8 @@ var ts; // // This keeps the expression as an expression, while ensuring that the static parts // of it have been initialized by the time it is used. - var staticProperties = getInitializedProperties(node, /*static:*/ true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 186 /* ClassExpression */; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 188 /* ClassExpression */; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0 /* Auto */); @@ -34884,7 +35519,7 @@ var ts; // emit name if // - node has a name // - this is default export with static initializers - if ((node.name || (node.flags & 512 /* Default */ && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if ((node.name || (node.flags & 512 /* Default */ && (staticProperties.length > 0 || modulekind !== 5 /* ES6 */))) && !thisNodeIsDecorated) { write(" "); emitDeclarationName(node); } @@ -34895,14 +35530,12 @@ var ts; } write(" {"); increaseIndent(); - scopeEmitStart(node); writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES6AndHigher(node); decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now. // For a decorated class, we need to assign its name (if it has one). This is because we emit // the class as a class expression to avoid the double-binding of the identifier: @@ -34924,7 +35557,7 @@ var ts; var property = staticProperties_1[_a]; write(","); writeLine(); - emitPropertyDeclaration(node, property, /*receiver:*/ tempVariable, /*isExpression:*/ true); + emitPropertyDeclaration(node, property, /*receiver*/ tempVariable, /*isExpression*/ true); } write(","); writeLine(); @@ -34937,27 +35570,37 @@ var ts; emitPropertyDeclarations(node, staticProperties); emitDecoratorsOfClass(node); } - // If this is an exported class, but not on the top level (i.e. on an internal - // module), export it - if (!isES6ExportedDeclaration(node) && (node.flags & 2 /* Export */)) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); + if (!(node.flags & 2 /* Export */)) { + return; } - else if (isES6ExportedDeclaration(node) && (node.flags & 512 /* Default */) && thisNodeIsDecorated) { - // if this is a top level default export of decorated class, write the export after the declaration. - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); + if (modulekind !== 5 /* ES6 */) { + emitExportMemberAssignment(node); + } + else { + // If this is an exported class, but not on the top level (i.e. on an internal + // module), export it + if (node.flags & 512 /* Default */) { + // if this is a top level default export of decorated class, write the export after the declaration. + if (thisNodeIsDecorated) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } + } + else if (node.parent.kind !== 250 /* SourceFile */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emitDeclarationName(node); + emitEnd(node); + write(";"); + } } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { // source file level classes in system modules are hoisted so 'var's for them are already defined if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); @@ -34982,7 +35625,6 @@ var ts; tempParameters = undefined; computedPropertyNamesToGeneratedNames = undefined; increaseIndent(); - scopeEmitStart(node); if (baseTypeNode) { writeLine(); emitStart(baseTypeNode); @@ -34994,7 +35636,7 @@ var ts; writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES5AndLower(node); - emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ true)); + emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ true)); writeLine(); emitDecoratorsOfClass(node); writeLine(); @@ -35013,18 +35655,17 @@ var ts; decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); emitStart(node); - write(")("); + write("("); if (baseTypeNode) { emit(baseTypeNode.expression); } - write(")"); - if (node.kind === 214 /* ClassDeclaration */) { + write("))"); + if (node.kind === 216 /* ClassDeclaration */) { write(";"); } emitEnd(node); - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { emitExportMemberAssignment(node); } } @@ -35042,9 +35683,9 @@ var ts; function emitDecoratorsOfConstructor(node) { var decorators = node.decorators; var constructor = ts.getFirstConstructorWithBody(node); - var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated); + var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); // skip decoration of the constructor if neither it nor its parameters are decorated - if (!decorators && !hasDecoratedParameters) { + if (!decorators && !firstParameterDecorator) { return; } // Emit the call to __decorate. Given the class: @@ -35058,25 +35699,24 @@ var ts; // C = __decorate([dec], C); // writeLine(); - emitStart(node); + emitStart(node.decorators || firstParameterDecorator); emitDeclarationName(node); write(" = __decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); + } emitSerializedTypeMetadata(node, /*leadingComma*/ argumentsWritten >= 0); decreaseIndent(); writeLine(); write("], "); emitDeclarationName(node); - write(");"); - emitEnd(node); + write(")"); + emitEnd(node.decorators || firstParameterDecorator); + write(";"); writeLine(); } function emitDecoratorsOfMembers(node, staticFlag) { @@ -35090,10 +35730,6 @@ var ts; if (!ts.nodeCanBeDecorated(member)) { continue; } - // skip a member if it or any of its parameters are not decorated - if (!ts.nodeOrChildIsDecorated(member)) { - continue; - } // skip an accessor declaration if it is not the first accessor var decorators = void 0; var functionLikeMember = void 0; @@ -35117,6 +35753,11 @@ var ts; functionLikeMember = member; } } + var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); + // skip a member if it or any of its parameters are not decorated + if (!decorators && !firstParameterDecorator) { + continue; + } // Emit the call to __decorate. Given the following: // // class C { @@ -35148,26 +35789,22 @@ var ts; // ], C.prototype, "prop"); // writeLine(); - emitStart(member); + emitStart(decorators || firstParameterDecorator); write("__decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + } emitSerializedTypeMetadata(member, argumentsWritten > 0); decreaseIndent(); writeLine(); write("], "); - emitStart(member.name); emitClassMemberPrefix(node, member); write(", "); emitExpressionForPropertyName(member.name); - emitEnd(member.name); if (languageVersion > 0 /* ES3 */) { if (member.kind !== 141 /* PropertyDeclaration */) { // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. @@ -35180,8 +35817,9 @@ var ts; write(", void 0"); } } - write(");"); - emitEnd(member); + write(")"); + emitEnd(decorators || firstParameterDecorator); + write(";"); writeLine(); } } @@ -35194,15 +35832,13 @@ var ts; if (ts.nodeIsDecorated(parameter)) { var decorators = parameter.decorators; argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); write("__param(" + parameterIndex + ", "); emit(decorator.expression); write(")"); - emitEnd(decorator); }); leadingComma = true; } - ++parameterIndex; + parameterIndex++; } } return argumentsWritten; @@ -35235,7 +35871,7 @@ var ts; // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch (node.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: case 143 /* MethodDeclaration */: case 146 /* SetAccessor */: return true; @@ -35255,7 +35891,7 @@ var ts; // // For rules on serializing type annotations, see `serializeTypeNode`. switch (node.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: write("Function"); return; case 141 /* PropertyDeclaration */: @@ -35299,7 +35935,7 @@ var ts; write("Boolean"); return; case 130 /* StringKeyword */: - case 9 /* StringLiteral */: + case 162 /* StringLiteralType */: write("String"); return; case 128 /* NumberKeyword */: @@ -35316,6 +35952,7 @@ var ts; case 158 /* UnionType */: case 159 /* IntersectionType */: case 117 /* AnyKeyword */: + case 161 /* ThisType */: break; default: ts.Debug.fail("Cannot serialize unexpected type node."); @@ -35331,8 +35968,7 @@ var ts; location = location.parent; } // Clone the type name and parent it to a location outside of the current declaration. - var typeName = ts.cloneEntityName(node.typeName); - typeName.parent = location; + var typeName = ts.cloneEntityName(node.typeName, location); var result = resolver.getTypeReferenceSerializationKind(typeName); switch (result) { case ts.TypeReferenceSerializationKind.Unknown: @@ -35389,7 +36025,7 @@ var ts; // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. if (node) { var valueDeclaration; - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -35484,9 +36120,10 @@ var ts; } if (!shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted - if (!(node.flags & 2 /* Export */) || isES6ExportedDeclaration(node)) { + var isES6ExportedEnum = isES6ExportedDeclaration(node); + if (!(node.flags & 2 /* Export */) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 219 /* EnumDeclaration */))) { emitStart(node); - if (isES6ExportedDeclaration(node)) { + if (isES6ExportedEnum) { write("export "); } write("var "); @@ -35503,12 +36140,10 @@ var ts; emitEnd(node.name); write(") {"); increaseIndent(); - scopeEmitStart(node); emitLines(node.members); decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); write(")("); emitModuleMemberName(node); write(" || ("); @@ -35568,7 +36203,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 220 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -35579,6 +36214,9 @@ var ts; function isModuleMergedWithES6Class(node) { return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 32768 /* LexicalModuleMergesWithClass */); } + function isFirstDeclarationOfKind(node, declarations, kind) { + return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); + } function emitModuleDeclaration(node) { // Emit only if this module is non-ambient. var shouldEmit = shouldEmitModuleDeclaration(node); @@ -35588,15 +36226,18 @@ var ts; var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); if (emitVarForModule) { - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); + var isES6ExportedNamespace = isES6ExportedDeclaration(node); + if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 220 /* ModuleDeclaration */)) { + emitStart(node); + if (isES6ExportedNamespace) { + write("export "); + } + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); } emitStart(node); write("(function ("); @@ -35604,7 +36245,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 219 /* ModuleBlock */) { + if (node.body.kind === 221 /* ModuleBlock */) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; @@ -35620,7 +36261,6 @@ var ts; else { write("{"); increaseIndent(); - scopeEmitStart(node); emitCaptureThisForNodeIfNecessary(node); writeLine(); emit(node.body); @@ -35628,7 +36268,6 @@ var ts; writeLine(); var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; emitToken(16 /* CloseBraceToken */, moduleBlock.statements.end); - scopeEmitEnd(); } write(")("); // write moduleDecl = containingModule.m only if it is not exported es6 module member @@ -35682,16 +36321,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 223 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 226 /* NamespaceImport */) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 222 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 224 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -35719,7 +36358,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 226 /* NamespaceImport */) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -35745,7 +36384,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 2 /* Export */) !== 0; + var isExportedImport = node.kind === 223 /* ImportEqualsDeclaration */ && (node.flags & 2 /* Export */) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (modulekind !== 2 /* AMD */) { emitLeadingComments(node); @@ -35764,7 +36403,7 @@ var ts; // import { x, y } from "foo" // import d, * as x from "foo" // import d, { x, y } from "foo" - var isNakedImport = 222 /* ImportDeclaration */ && !node.importClause; + var isNakedImport = 224 /* ImportDeclaration */ && !node.importClause; if (!isNakedImport) { write("var "); write(getGeneratedNameForNode(node)); @@ -35882,15 +36521,17 @@ var ts; } else { // export * from "foo" - writeLine(); - write("__export("); - if (modulekind !== 2 /* AMD */) { - emitRequire(ts.getExternalModuleName(node)); + if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + writeLine(); + write("__export("); + if (modulekind !== 2 /* AMD */) { + emitRequire(ts.getExternalModuleName(node)); + } + else { + write(generatedName); + } + write(");"); } - else { - write(generatedName); - } - write(");"); } emitEnd(node); } @@ -35941,8 +36582,8 @@ var ts; write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 213 /* FunctionDeclaration */ && - expression.kind !== 214 /* ClassDeclaration */) { + if (expression.kind !== 215 /* FunctionDeclaration */ && + expression.kind !== 216 /* ClassDeclaration */) { write(";"); } emitEnd(node); @@ -35975,11 +36616,11 @@ var ts; externalImports = []; exportSpecifiers = {}; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { // import "mod" @@ -35989,18 +36630,20 @@ var ts; externalImports.push(node); } break; - case 221 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 232 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { + case 223 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 234 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { // import x = require("mod") where x is referenced externalImports.push(node); } break; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" - externalImports.push(node); - hasExportStars = true; + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } } else if (resolver.isValueAliasDeclaration(node)) { // export { x, y } from "mod" where at least one export is a value symbol @@ -36011,12 +36654,12 @@ var ts; // export { x, y } for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_26 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_26] || (exportSpecifiers[name_26] = [])).push(specifier); + var name_24 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_24] || (exportSpecifiers[name_24] = [])).push(specifier); } } break; - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; @@ -36026,7 +36669,7 @@ var ts; } } function emitExportStarHelper() { - if (hasExportStars) { + if (hasExportStarsToExportValues) { writeLine(); write("function __export(m) {"); increaseIndent(); @@ -36042,14 +36685,20 @@ var ts; if (namespaceDeclaration && !isDefaultImport(node)) { return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); } - if (node.kind === 222 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 224 /* ImportDeclaration */ && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 228 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 230 /* ExportDeclaration */ && node.moduleSpecifier) { return getGeneratedNameForNode(node); } } - function getExternalModuleNameText(importNode) { + function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { + if (emitRelativePathAsModuleName) { + var name_25 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_25) { + return "\"" + name_25 + "\""; + } + } var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9 /* StringLiteral */) { return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); @@ -36065,8 +36714,8 @@ var ts; for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { var importNode = externalImports_1[_a]; // do not create variable declaration for exports and imports that lack import clause - var skipNode = importNode.kind === 228 /* ExportDeclaration */ || - (importNode.kind === 222 /* ImportDeclaration */ && !importNode.importClause); + var skipNode = importNode.kind === 230 /* ExportDeclaration */ || + (importNode.kind === 224 /* ImportDeclaration */ && !importNode.importClause); if (skipNode) { continue; } @@ -36088,7 +36737,7 @@ var ts; // should always win over entries with similar names that were added via star exports // to support this we store names of local/indirect exported entries in a set. // this set is used to filter names brought by star expors. - if (!hasExportStars) { + if (!hasExportStarsToExportValues) { // local names set is needed only in presence of star exports return undefined; } @@ -36099,7 +36748,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; - if (externalImport.kind === 228 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 230 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -36115,7 +36764,7 @@ var ts; increaseIndent(); var started = false; if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; ++i) { + for (var i = 0; i < exportedDeclarations.length; i++) { // write name of exported declaration, i.e 'export var x...' writeExportedName(exportedDeclarations[i]); } @@ -36131,7 +36780,7 @@ var ts; } for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 228 /* ExportDeclaration */) { + if (externalImport.kind !== 230 /* ExportDeclaration */) { continue; } var exportDecl = externalImport; @@ -36217,14 +36866,14 @@ var ts; writeLine(); write("var "); var seen = {}; - for (var i = 0; i < hoistedVars.length; ++i) { + for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_27 = local.kind === 69 /* Identifier */ + var name_26 = local.kind === 69 /* Identifier */ ? local : local.name; - if (name_27) { + if (name_26) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables - var text = ts.unescapeIdentifier(name_27.text); + var text = ts.unescapeIdentifier(name_26.text); if (ts.hasProperty(seen, text)) { continue; } @@ -36235,7 +36884,7 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 214 /* ClassDeclaration */ || local.kind === 218 /* ModuleDeclaration */ || local.kind === 217 /* EnumDeclaration */) { + if (local.kind === 216 /* ClassDeclaration */ || local.kind === 220 /* ModuleDeclaration */ || local.kind === 219 /* EnumDeclaration */) { emitDeclarationName(local); } else { @@ -36269,21 +36918,21 @@ var ts; if (node.flags & 4 /* Ambient */) { return; } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 215 /* FunctionDeclaration */) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 216 /* ClassDeclaration */) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 217 /* EnumDeclaration */) { + if (node.kind === 219 /* EnumDeclaration */) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -36292,7 +36941,7 @@ var ts; } return; } - if (node.kind === 218 /* ModuleDeclaration */) { + if (node.kind === 220 /* ModuleDeclaration */) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -36301,17 +36950,17 @@ var ts; } return; } - if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) { + if (node.kind === 213 /* VariableDeclaration */ || node.kind === 165 /* BindingElement */) { if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) { - var name_28 = node.name; - if (name_28.kind === 69 /* Identifier */) { + var name_27 = node.name; + if (name_27.kind === 69 /* Identifier */) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_28); + hoistedVars.push(name_27); } else { - ts.forEachChild(name_28, visit); + ts.forEachChild(name_27, visit); } } return; @@ -36342,7 +36991,7 @@ var ts; // if block scoped variables are nested in some another block then // no other functions can use them except ones that are defined at least in the same block return (ts.getCombinedNodeFlags(node) & 24576 /* BlockScoped */) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 248 /* SourceFile */; + ts.getEnclosingBlockScopeContainer(node).kind === 250 /* SourceFile */; } function isCurrentFileSystemExternalModule() { return modulekind === 4 /* System */ && isCurrentFileExternalModule; @@ -36402,7 +37051,7 @@ var ts; } function emitSetters(exportStarFunction, dependencyGroups) { write("setters:["); - for (var i = 0; i < dependencyGroups.length; ++i) { + for (var i = 0; i < dependencyGroups.length; i++) { if (i !== 0) { write(","); } @@ -36417,21 +37066,21 @@ var ts; var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // fall-through - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== ""); writeLine(); // save import into the local write(importVariableName + " = " + parameterName + ";"); writeLine(); break; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== ""); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -36444,7 +37093,7 @@ var ts; write(exportFunctionForFile + "({"); writeLine(); increaseIndent(); - for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) { + for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; i_2++) { if (i_2 !== 0) { write(","); writeLine(); @@ -36461,6 +37110,8 @@ var ts; write("});"); } else { + // collectExternalModuleInfo prefilters star exports to keep only ones that export values + // this means that check 'resolver.moduleExportsSomeValue' is redundant and can be omitted here writeLine(); // export * from 'foo' // emit as: @@ -36481,17 +37132,17 @@ var ts; write("execute: function() {"); increaseIndent(); writeLine(); - for (var i = startIndex; i < node.statements.length; ++i) { + for (var i = startIndex; i < node.statements.length; i++) { var statement = node.statements[i]; switch (statement.kind) { // - function declarations are not emitted because they were already hoisted // - import declarations are not emitted since they are already handled in setters // - export declarations with module specifiers are not emitted since they were already written in setters // - export declarations without module specifiers are emitted preserving the order - case 213 /* FunctionDeclaration */: - case 222 /* ImportDeclaration */: + case 215 /* FunctionDeclaration */: + case 224 /* ImportDeclaration */: continue; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: if (!statement.moduleSpecifier) { for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { var element = _b[_a]; @@ -36500,7 +37151,7 @@ var ts; } } continue; - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { // - import equals declarations that import external modules are not emitted continue; @@ -36540,8 +37191,8 @@ var ts; write("["); var groupIndices = {}; var dependencyGroups = []; - for (var i = 0; i < externalImports.length; ++i) { - var text = getExternalModuleNameText(externalImports[i]); + for (var i = 0; i < externalImports.length; i++) { + var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); if (ts.hasProperty(groupIndices, text)) { // deduplicate/group entries in dependency list by the dependency name var groupIndex = groupIndices[text]; @@ -36555,18 +37206,12 @@ var ts; if (i !== 0) { write(", "); } - if (emitRelativePathAsModuleName) { - var name_29 = getExternalModuleNameFromDeclaration(host, resolver, externalImports[i]); - if (name_29) { - text = "\"" + name_29 + "\""; - } - } write(text); } write("], function(" + exportFunctionForFile + ") {"); writeLine(); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitSystemModuleBody(node, dependencyGroups, startIndex); @@ -36596,13 +37241,7 @@ var ts; for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { var importNode = externalImports_4[_c]; // Find the name of the external module - var externalModuleName = getExternalModuleNameText(importNode); - if (emitRelativePathAsModuleName) { - var name_30 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_30) { - externalModuleName = "\"" + name_30 + "\""; - } - } + var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); // Find the name of the module alias, if there is one var importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { @@ -36662,7 +37301,7 @@ var ts; writeModuleName(node, emitRelativePathAsModuleName); emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36673,7 +37312,7 @@ var ts; write("});"); } function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false, /*ensureUseStrict*/ true); emitEmitHelpers(node); collectExternalModuleInfo(node); emitExportStarHelper(); @@ -36693,7 +37332,7 @@ var ts; writeLines(" }\n})("); emitAMDFactoryHeader(dependencyNames); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36707,7 +37346,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); @@ -36770,7 +37409,9 @@ var ts; // Replace entities like   result = result.replace(/&(\w+);/g, function (s, m) { if (entities[m] !== undefined) { - return String.fromCharCode(entities[m]); + var ch = String.fromCharCode(entities[m]); + // " needs to be escaped + return ch === "\"" ? "\\\"" : ch; } else { return s; @@ -36822,24 +37463,41 @@ var ts; } } } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { + function isUseStrictPrologue(node) { + return !!node.expression.text.match(/use strict/); + } + function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { + if (writeUseStrict) { + if (startWithNewLine) { + writeLine(); + } + write("\"use strict\";"); + } + } + function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { + var foundUseStrict = false; + for (var i = 0; i < statements.length; i++) { if (ts.isPrologueDirective(statements[i])) { + if (isUseStrictPrologue(statements[i])) { + foundUseStrict = true; + } if (startWithNewLine || i > 0) { writeLine(); } emit(statements[i]); } else { + ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); // return index of the first non prologue directive return i; } } + ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); return statements.length; } function writeLines(text) { var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; ++i) { + for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (line.length) { writeLine(); @@ -36879,7 +37537,7 @@ var ts; emitShebang(); emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - if (root || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { + if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */]; emitModule(node); } @@ -36893,7 +37551,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36901,6 +37559,9 @@ var ts; } emitLeadingComments(node.endOfFileToken); } + function emit(node) { + emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); + } function emitNodeWithCommentsAndWithoutSourcemap(node) { emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); } @@ -36923,6 +37584,13 @@ var ts; } } } + function emitNodeWithSourceMap(node) { + if (node) { + emitStart(node); + emitNodeWithoutSourceMap(node); + emitEnd(node); + } + } function emitNodeWithoutSourceMap(node) { if (node) { emitJavaScriptWorker(node); @@ -36932,24 +37600,24 @@ var ts; switch (node.kind) { // All of these entities are emitted in a specialized fashion. As such, we allow // the specialized methods for each to handle the comments on the nodes. - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 227 /* ExportAssignment */: + case 217 /* InterfaceDeclaration */: + case 215 /* FunctionDeclaration */: + case 224 /* ImportDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 229 /* ExportAssignment */: return true; } } function shouldEmitLeadingAndTrailingComments(node) { switch (node.kind) { - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: // Only emit the leading/trailing comments for a module if we're actually // emitting the module as well. return shouldEmitModuleDeclaration(node); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: // Only emit the leading/trailing comments for an enum if we're actually // emitting the module as well. return shouldEmitEnumDeclaration(node); @@ -36961,9 +37629,9 @@ var ts; // then we don't want to emit comments when we emit the body. It will have already // been taken care of when we emitted the 'return' statement for the function // expression body. - if (node.kind !== 192 /* Block */ && + if (node.kind !== 194 /* Block */ && node.parent && - node.parent.kind === 174 /* ArrowFunction */ && + node.parent.kind === 176 /* ArrowFunction */ && node.parent.body === node && compilerOptions.target <= 1 /* ES5 */) { return false; @@ -37002,142 +37670,142 @@ var ts; case 13 /* TemplateMiddle */: case 14 /* TemplateTail */: return emitLiteral(node); - case 183 /* TemplateExpression */: + case 185 /* TemplateExpression */: return emitTemplateExpression(node); - case 190 /* TemplateSpan */: + case 192 /* TemplateSpan */: return emitTemplateSpan(node); - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: + case 235 /* JsxElement */: + case 236 /* JsxSelfClosingElement */: return emitJsxElement(node); - case 236 /* JsxText */: + case 238 /* JsxText */: return emitJsxText(node); - case 240 /* JsxExpression */: + case 242 /* JsxExpression */: return emitJsxExpression(node); case 135 /* QualifiedName */: return emitQualifiedName(node); - case 161 /* ObjectBindingPattern */: + case 163 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 162 /* ArrayBindingPattern */: + case 164 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 163 /* BindingElement */: + case 165 /* BindingElement */: return emitBindingElement(node); - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return emitArrayLiteral(node); - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return emitObjectLiteral(node); - case 245 /* PropertyAssignment */: + case 247 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 246 /* ShorthandPropertyAssignment */: + case 248 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); case 136 /* ComputedPropertyName */: return emitComputedPropertyName(node); - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: return emitPropertyAccess(node); - case 167 /* ElementAccessExpression */: + case 169 /* ElementAccessExpression */: return emitIndexedAccess(node); - case 168 /* CallExpression */: + case 170 /* CallExpression */: return emitCallExpression(node); - case 169 /* NewExpression */: + case 171 /* NewExpression */: return emitNewExpression(node); - case 170 /* TaggedTemplateExpression */: + case 172 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 171 /* TypeAssertionExpression */: + case 173 /* TypeAssertionExpression */: return emit(node.expression); - case 189 /* AsExpression */: + case 191 /* AsExpression */: return emit(node.expression); - case 172 /* ParenthesizedExpression */: + case 174 /* ParenthesizedExpression */: return emitParenExpression(node); - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return emitFunctionDeclaration(node); - case 175 /* DeleteExpression */: + case 177 /* DeleteExpression */: return emitDeleteExpression(node); - case 176 /* TypeOfExpression */: + case 178 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 177 /* VoidExpression */: + case 179 /* VoidExpression */: return emitVoidExpression(node); - case 178 /* AwaitExpression */: + case 180 /* AwaitExpression */: return emitAwaitExpression(node); - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 180 /* PostfixUnaryExpression */: + case 182 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return emitBinaryExpression(node); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return emitConditionalExpression(node); - case 185 /* SpreadElementExpression */: + case 187 /* SpreadElementExpression */: return emitSpreadElementExpression(node); - case 184 /* YieldExpression */: + case 186 /* YieldExpression */: return emitYieldExpression(node); - case 187 /* OmittedExpression */: + case 189 /* OmittedExpression */: return; - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 194 /* Block */: + case 221 /* ModuleBlock */: return emitBlock(node); - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: return emitVariableStatement(node); - case 194 /* EmptyStatement */: + case 196 /* EmptyStatement */: return write(";"); - case 195 /* ExpressionStatement */: + case 197 /* ExpressionStatement */: return emitExpressionStatement(node); - case 196 /* IfStatement */: + case 198 /* IfStatement */: return emitIfStatement(node); - case 197 /* DoStatement */: + case 199 /* DoStatement */: return emitDoStatement(node); - case 198 /* WhileStatement */: + case 200 /* WhileStatement */: return emitWhileStatement(node); - case 199 /* ForStatement */: + case 201 /* ForStatement */: return emitForStatement(node); - case 201 /* ForOfStatement */: - case 200 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 202 /* ForInStatement */: return emitForInOrForOfStatement(node); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 204 /* ContinueStatement */: + case 205 /* BreakStatement */: return emitBreakOrContinueStatement(node); - case 204 /* ReturnStatement */: + case 206 /* ReturnStatement */: return emitReturnStatement(node); - case 205 /* WithStatement */: + case 207 /* WithStatement */: return emitWithStatement(node); - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: return emitSwitchStatement(node); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: return emitCaseOrDefaultClause(node); - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: return emitLabeledStatement(node); - case 208 /* ThrowStatement */: + case 210 /* ThrowStatement */: return emitThrowStatement(node); - case 209 /* TryStatement */: + case 211 /* TryStatement */: return emitTryStatement(node); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return emitCatchClause(node); - case 210 /* DebuggerStatement */: + case 212 /* DebuggerStatement */: return emitDebuggerStatement(node); - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: return emitClassExpression(node); - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: return emitClassDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 247 /* EnumMember */: + case 249 /* EnumMember */: return emitEnumMember(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: return emitImportDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: return emitExportDeclaration(node); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: return emitExportAssignment(node); - case 248 /* SourceFile */: + case 250 /* SourceFile */: return emitSourceFileNode(node); } } @@ -37176,7 +37844,7 @@ var ts; function getLeadingCommentsToEmit(node) { // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments if (node.parent) { - if (node.parent.kind === 248 /* SourceFile */ || node.pos !== node.parent.pos) { + if (node.parent.kind === 250 /* SourceFile */ || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { // get comments without detached comments return getLeadingCommentsWithoutDetachedComments(); @@ -37191,7 +37859,7 @@ var ts; function getTrailingCommentsToEmit(node) { // Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments if (node.parent) { - if (node.parent.kind === 248 /* SourceFile */ || node.end !== node.parent.end) { + if (node.parent.kind === 250 /* SourceFile */ || node.end !== node.parent.end) { return ts.getTrailingCommentRanges(currentText, node.end); } } @@ -37200,10 +37868,10 @@ var ts; * Emit comments associated with node that will not be emitted into JS file */ function emitCommentsOnNotEmittedNode(node) { - emitLeadingCommentsWorker(node, /*isEmittedNode:*/ false); + emitLeadingCommentsWorker(node, /*isEmittedNode*/ false); } function emitLeadingComments(node) { - return emitLeadingCommentsWorker(node, /*isEmittedNode:*/ true); + return emitLeadingCommentsWorker(node, /*isEmittedNode*/ true); } function emitLeadingCommentsWorker(node, isEmittedNode) { if (compilerOptions.removeComments) { @@ -37228,7 +37896,7 @@ var ts; } ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); } function emitTrailingComments(node) { if (compilerOptions.removeComments) { @@ -37280,18 +37948,31 @@ var ts; } } } + function writeComment(text, lineMap, writer, comment, newLine) { + emitPos(comment.pos); + ts.writeCommentRange(text, lineMap, writer, comment, newLine); + emitPos(comment.end); + } function emitShebang() { var shebang = ts.getShebang(currentText); if (shebang) { write(shebang); + writeLine(); } } var _a, _b; } - function emitFile(jsFilePath, sourceFile) { - emitJavaScript(jsFilePath, sourceFile); - if (compilerOptions.declaration) { - ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics); + function emitFile(_a, sourceFiles, isBundledEmit) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + // Make sure not to write js File and source map file if any of them cannot be written + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; + } + if (declarationFilePath) { + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } } } @@ -37309,10 +37990,10 @@ var ts; /** The version of the TypeScript compiler release */ var emptyArray = []; ts.version = "1.8.0"; - function findConfigFile(searchPath) { + function findConfigFile(searchPath, fileExists) { var fileName = "tsconfig.json"; while (true) { - if (ts.sys.fileExists(fileName)) { + if (fileExists(fileName)) { return fileName; } var parentPath = ts.getDirectoryPath(searchPath); @@ -37336,21 +38017,22 @@ var ts; ? compilerOptions.moduleResolution : compilerOptions.module === 1 /* CommonJS */ ? 2 /* NodeJs */ : 1 /* Classic */; switch (moduleResolution) { - case 2 /* NodeJs */: return nodeModuleNameResolver(moduleName, containingFile, host); + case 2 /* NodeJs */: return nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); case 1 /* Classic */: return classicNameResolver(moduleName, containingFile, compilerOptions, host); } } ts.resolveModuleName = resolveModuleName; - function nodeModuleNameResolver(moduleName, containingFile, host) { + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { var failedLookupLocations = []; var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolvedFileName = loadNodeModuleFromFile(ts.supportedJsExtensions, candidate, failedLookupLocations, host); + var resolvedFileName = loadNodeModuleFromFile(supportedExtensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, host); if (resolvedFileName) { return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }; } - resolvedFileName = loadNodeModuleFromDirectory(ts.supportedJsExtensions, candidate, failedLookupLocations, host); + resolvedFileName = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, host); return resolvedFileName ? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations } : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; @@ -37360,11 +38042,21 @@ var ts; } } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, host) { + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * 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 loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, onlyRecordFailures, host) { return ts.forEach(extensions, tryLoad); function tryLoad(ext) { var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (host.fileExists(fileName)) { + if (!onlyRecordFailures && host.fileExists(fileName)) { return fileName; } else { @@ -37373,9 +38065,10 @@ var ts; } } } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, host) { + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, host) { var packageJsonPath = ts.combinePaths(candidate, "package.json"); - if (host.fileExists(packageJsonPath)) { + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, host); + if (directoryExists && host.fileExists(packageJsonPath)) { var jsonContent; try { var jsonText = host.readFile(packageJsonPath); @@ -37385,8 +38078,9 @@ var ts; // gracefully handle if readFile fails or returns not JSON jsonContent = { typings: undefined }; } - if (jsonContent.typings) { - var result = loadNodeModuleFromFile(extensions, ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host); + if (typeof jsonContent.typings === "string") { + var path = ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)); + var result = loadNodeModuleFromFile(extensions, path, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(path), host), host); if (result) { return result; } @@ -37396,7 +38090,7 @@ var ts; // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results failedLookupLocation.push(packageJsonPath); } - return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, host); + return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, !directoryExists, host); } function loadModuleFromNodeModules(moduleName, directory, host) { var failedLookupLocations = []; @@ -37405,12 +38099,14 @@ var ts; var baseName = ts.getBaseFileName(directory); if (baseName !== "node_modules") { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, host); var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var result = loadNodeModuleFromFile(ts.supportedExtensions, candidate, failedLookupLocations, host); + // Load only typescript files irrespective of allowJs option if loading from node modules + var result = loadNodeModuleFromFile(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; } - result = loadNodeModuleFromDirectory(ts.supportedExtensions, candidate, failedLookupLocations, host); + result = loadNodeModuleFromDirectory(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; } @@ -37436,10 +38132,10 @@ var ts; var searchName; var failedLookupLocations = []; var referencedSourceFile; - var extensions = compilerOptions.allowNonTsExtensions ? ts.supportedJsExtensions : ts.supportedExtensions; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); while (true) { searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - referencedSourceFile = ts.forEach(extensions, function (extension) { + referencedSourceFile = ts.forEach(supportedExtensions, function (extension) { if (extension === ".tsx" && !compilerOptions.jsx) { // resolve .tsx files only if jsx support is enabled // 'logical not' handles both undefined and None cases @@ -37540,14 +38236,15 @@ var ts; getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); } + readFile: function (fileName) { return ts.sys.readFile(fileName); }, + directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); } }; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -37585,8 +38282,11 @@ var ts; var noDiagnosticsTypeChecker; var classifiableNames; var skipDefaultLib = options.noLib; + var supportedExtensions = ts.getSupportedExtensions(options); var start = new Date().getTime(); host = host || createCompilerHost(options); + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var currentDirectory = host.getCurrentDirectory(); var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) @@ -37603,24 +38303,23 @@ var ts; (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx)) { + (oldOptions.jsx !== options.jsx) || + (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } if (!tryReuseStructureFromOldProgram()) { - ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // Do not process the default library if: // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. if (!skipDefaultLib) { - processRootFile(host.getDefaultLibFileName(options), true); + processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true); } } - verifyCompilerOptions(); // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; - ts.programTime += new Date().getTime() - start; program = { getRootFileNames: function () { return rootNames; }, getSourceFile: getSourceFile, @@ -37634,7 +38333,7 @@ var ts; getTypeChecker: getTypeChecker, getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, - getCommonSourceDirectory: function () { return commonSourceDirectory; }, + getCommonSourceDirectory: getCommonSourceDirectory, emit: emit, getCurrentDirectory: function () { return currentDirectory; }, getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, @@ -37643,7 +38342,27 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; } }; + verifyCompilerOptions(); + ts.programTime += new Date().getTime() - start; return program; + function getCommonSourceDirectory() { + if (typeof commonSourceDirectory === "undefined") { + if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + // If a rootDir is specified and is valid use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(files); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } function getClassifiableNames() { if (!classifiableNames) { // Initialize a checker so that all our files are bound. @@ -37699,7 +38418,7 @@ var ts; var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct - for (var i = 0; i < moduleNames.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var newResolution = resolutions[i]; var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); var resolutionChanged = oldResolution @@ -37724,7 +38443,7 @@ var ts; newSourceFiles.push(newSourceFile); } // update fileName -> file mapping - for (var i = 0, len = newSourceFiles.length; i < len; ++i) { + for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; @@ -37745,7 +38464,8 @@ var ts; getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFiles: program.getSourceFiles, - writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }) + writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }), + isEmitBlocked: isEmitBlocked }; } function getDiagnosticsProducingTypeChecker() { @@ -37758,12 +38478,18 @@ var ts; var _this = this; return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { // If the noEmitOnError flag is set, then check if we have any errors so far. If so, // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError && getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken).length > 0) { - return { diagnostics: [], sourceMaps: undefined, emitSkipped: true }; + if (options.noEmitOnError) { + var preEmitDiagnostics = getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken); + if (preEmitDiagnostics.length > 0) { + return { diagnostics: preEmitDiagnostics, sourceMaps: undefined, emitSkipped: true }; + } } // Create the emit resolver outside of the "emitTime" tracking code below. That way // any cost associated with it (like type checking) are appropriate associated with @@ -37833,12 +38559,164 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + // For JavaScript files, we don't want to report the normal typescript semantic errors. + // Instead, we just report errors for using TypeScript-only constructs from within a + // JavaScript file. + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? + getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : + typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); } + function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var diagnostics = []; + walk(sourceFile); + return diagnostics; + function walk(node) { + if (!node) { + return false; + } + switch (node.kind) { + case 223 /* ImportEqualsDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return true; + case 229 /* ExportAssignment */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return true; + case 216 /* ClassDeclaration */: + var classDeclaration = node; + if (checkModifiers(classDeclaration.modifiers) || + checkTypeParameters(classDeclaration.typeParameters)) { + return true; + } + break; + case 245 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 106 /* ImplementsKeyword */) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 217 /* InterfaceDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 220 /* ModuleDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 218 /* TypeAliasDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return true; + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 175 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 176 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + var functionDeclaration = node; + if (checkModifiers(functionDeclaration.modifiers) || + checkTypeParameters(functionDeclaration.typeParameters) || + checkTypeAnnotation(functionDeclaration.type)) { + return true; + } + break; + case 195 /* VariableStatement */: + var variableStatement = node; + if (checkModifiers(variableStatement.modifiers)) { + return true; + } + break; + case 213 /* VariableDeclaration */: + var variableDeclaration = node; + if (checkTypeAnnotation(variableDeclaration.type)) { + return true; + } + break; + case 170 /* CallExpression */: + case 171 /* 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)); + return true; + } + break; + case 138 /* 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)); + return true; + } + if (parameter.questionToken) { + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return true; + } + if (parameter.type) { + diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 141 /* PropertyDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 219 /* EnumDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 173 /* TypeAssertionExpression */: + var typeAssertionExpression = node; + diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return true; + case 139 /* Decorator */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); + return true; + } + return ts.forEachChild(node, walk); + } + 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)); + return true; + } + return false; + } + function checkTypeAnnotation(type) { + if (type) { + diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkModifiers(modifiers) { + if (modifiers) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 122 /* DeclareKeyword */: + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + // These are all legal modifiers. + case 113 /* StaticKeyword */: + case 82 /* ExportKeyword */: + case 74 /* ConstKeyword */: + case 77 /* DefaultKeyword */: + case 115 /* AbstractKeyword */: + } + } + } + return false; + } + }); + } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { return runWithCancellationToken(function () { if (!ts.isDeclarationFile(sourceFile)) { @@ -37880,16 +38758,16 @@ var ts; var imports; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; - collect(node, /* allowRelativeModuleNames */ true, /* collectOnlyRequireCalls */ false); + collect(node, /*allowRelativeModuleNames*/ true, /*collectOnlyRequireCalls*/ false); } file.imports = imports || emptyArray; return; function collect(node, allowRelativeModuleNames, collectOnlyRequireCalls) { if (!collectOnlyRequireCalls) { switch (node.kind) { - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: + case 224 /* ImportDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 230 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) { break; @@ -37901,7 +38779,7 @@ var ts; (imports || (imports = [])).push(moduleNameExpr); } break; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) { // TypeScript 1.0 spec (April 2014): 12.1.6 // An AmbientExternalModuleDeclaration declares an external module. @@ -37912,7 +38790,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 12.1.6 // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules // only through top - level external module names. Relative external module names are not permitted. - collect(node, /* allowRelativeModuleNames */ false, collectOnlyRequireCalls); + collect(node, /*allowRelativeModuleNames*/ false, collectOnlyRequireCalls); }); } break; @@ -37923,7 +38801,7 @@ var ts; (imports || (imports = [])).push(node.arguments[0]); } else { - ts.forEachChild(node, function (node) { return collect(node, allowRelativeModuleNames, /* collectOnlyRequireCalls */ true); }); + ts.forEachChild(node, function (node) { return collect(node, allowRelativeModuleNames, /*collectOnlyRequireCalls*/ true); }); } } } @@ -37932,9 +38810,9 @@ var ts; var diagnosticArgument; var diagnostic; if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; + diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; @@ -37952,7 +38830,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -37977,12 +38855,12 @@ var ts; } } // Get source file from normalized fileName - function findSourceFile(fileName, normalizedAbsolutePath, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(normalizedAbsolutePath)) { - var file_1 = filesByName.get(normalizedAbsolutePath); + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + if (filesByName.contains(path)) { + var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== normalizedAbsolutePath) { + if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } return file_1; @@ -37996,17 +38874,17 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); - filesByName.set(normalizedAbsolutePath, file); + filesByName.set(path, file); if (file) { - file.path = normalizedAbsolutePath; + file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case - var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); + var existingFile = filesByNameIgnoreCase.get(path); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(normalizedAbsolutePath, file); + filesByNameIgnoreCase.set(path, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -38028,7 +38906,7 @@ var ts; function processReferencedFiles(file, basePath) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end); + processSourceFile(referencedFileName, /*isDefaultLib*/ false, file, ref.pos, ref.end); }); } function getCanonicalFileName(fileName) { @@ -38040,15 +38918,17 @@ var ts; file.resolvedModules = {}; var moduleNames = ts.map(file.imports, function (name) { return name.text; }); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); - for (var i = 0; i < file.imports.length; ++i) { + for (var i = 0; i < file.imports.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); if (resolution && !options.noResolve) { - var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /* isDefaultLib */ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { + // Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files, + // this check is ok. Otherwise this would be never true for javascript file if (!ts.isExternalModule(importedFile)) { - var start_2 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_2, file.imports[i].end - start_2, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); + var start_5 = ts.getTokenPosOfNode(file.imports[i], file); + fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { var firstRef = importedFile.referencedFiles[0]; @@ -38066,7 +38946,7 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var commonPathComponents; - ts.forEach(files, function (sourceFile) { + var failed = ts.forEach(files, function (sourceFile) { // Each file contributes into common source file path if (ts.isDeclarationFile(sourceFile)) { return; @@ -38079,10 +38959,10 @@ var ts; return; } for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; + // Failed to find any common path component + return true; } // New common path found that is 0 -> i-1 commonPathComponents.length = i; @@ -38094,6 +38974,10 @@ var ts; commonPathComponents.length = sourcePathComponents.length; } }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } if (!commonPathComponents) { return currentDirectory; } @@ -38103,8 +38987,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -38138,14 +39022,14 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); } - if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap")); - } } if (options.inlineSources) { if (!options.sourceMap && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); } + if (options.sourceRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); + } } if (options.out && options.outFile) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); @@ -38155,10 +39039,9 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } - if (options.sourceRoot) { + if (options.sourceRoot && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); } - return; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; @@ -38176,7 +39059,7 @@ var ts; else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && !options.module) { // 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_compile_modules_unless_the_module_flag_is_provided)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } // Cannot specify module gen target of es6 when below es6 if (options.module === 5 /* ES6 */ && languageVersion < 2 /* ES6 */) { @@ -38191,19 +39074,11 @@ var ts; if (options.outDir || options.sourceRoot || options.mapRoot) { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { - // If a rootDir is specified and is valid use it as the commonSourceDirectory - commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); - } - else { - // Compute the commonSourceDirectory from the input files - commonSourceDirectory = computeCommonSourceDirectory(files); - } - if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { - // Make sure directory path ends with directory separator so this string can directly - // used to replace with "" to get the relative path of the source file and the relative path doesn't - // start with / making it rooted path - commonSourceDirectory += ts.directorySeparator; + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { @@ -38220,10 +39095,47 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } + else if (options.allowJs && options.declaration) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } + if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit) { + var emitHost = getEmitHost(); + var emitFilesSeen = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); + // Report error if the output overwrites input file + if (filesByName.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + } + // Report error if multiple files write into same file + if (emitFilesSeen.contains(emitFilePath)) { + // Already seen the same emit file - report error + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + } + else { + emitFilesSeen.set(emitFilePath, true); + } + } + } + } + function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); } } ts.createProgram = createProgram; @@ -38284,6 +39196,11 @@ var ts; description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, error: ts.Diagnostics.Argument_for_jsx_must_be_preserve_or_react }, + { + name: "reactNamespace", + type: "string", + description: ts.Diagnostics.Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit + }, { name: "listFiles", type: "boolean" @@ -38509,6 +39426,16 @@ var ts; name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "allowJs", + type: "boolean", + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled } ]; var optionNameMapCache; @@ -38543,7 +39470,8 @@ var ts; function parseStrings(args) { var i = 0; while (i < args.length) { - var s = args[i++]; + var s = args[i]; + i++; if (s.charCodeAt(0) === 64 /* at */) { parseResponseFile(s.slice(1)); } @@ -38561,20 +39489,23 @@ var ts; } switch (opt.type) { case "number": - options[opt.name] = parseInt(args[i++]); + options[opt.name] = parseInt(args[i]); + i++; break; case "boolean": options[opt.name] = true; break; case "string": - options[opt.name] = args[i++] || ""; + options[opt.name] = args[i] || ""; + i++; break; // If not a primitive, the possible types are specified in what is effectively a map of options. default: - var map_2 = opt.type; - var key = (args[i++] || "").toLowerCase(); - if (ts.hasProperty(map_2, key)) { - options[opt.name] = map_2[key]; + var map_1 = opt.type; + var key = (args[i] || "").toLowerCase(); + i++; + if (ts.hasProperty(map_1, key)) { + options[opt.name] = map_1[key]; } else { errors.push(ts.createCompilerDiagnostic(opt.error)); @@ -38687,8 +39618,10 @@ var ts; * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json, host, basePath) { - var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors; + function parseJsonConfigFileContent(json, host, basePath, existingOptions) { + if (existingOptions === void 0) { existingOptions = {}; } + var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), optionsFromJsonConfigFile = _a.options, errors = _a.errors; + var options = ts.extend(existingOptions, optionsFromJsonConfigFile); return { options: options, fileNames: getFileNames(), @@ -38705,23 +39638,31 @@ var ts; } } else { + var filesSeen = {}; var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; - var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); - for (var i = 0; i < sysFiles.length; i++) { - var name_31 = sysFiles[i]; - if (ts.fileExtensionIs(name_31, ".d.ts")) { - var baseName = name_31.substr(0, name_31.length - ".d.ts".length); - if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) { - fileNames.push(name_31); + var supportedExtensions = ts.getSupportedExtensions(options); + ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); + // Get files of supported extensions in their order of resolution + for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; + var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); + for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { + var fileName = filesInDirWithExtension_1[_a]; + // .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension, + // lets pick them when its turn comes up + if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { + continue; } - } - else if (ts.fileExtensionIs(name_31, ".ts")) { - if (!ts.contains(sysFiles, name_31 + "x")) { - fileNames.push(name_31); + // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files) + // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation + if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { + var baseName = fileName.substr(0, fileName.length - extension.length); + if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { + continue; + } } - } - else { - fileNames.push(name_31); + filesSeen[fileName] = true; + fileNames.push(fileName); } } } @@ -38845,7 +39786,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 174 /* ArrowFunction */; + return ts.isFunctionBlock(node) && node.parent.kind !== 176 /* ArrowFunction */; } var depth = 0; var maxDepth = 20; @@ -38857,7 +39798,7 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 192 /* Block */: + case 194 /* Block */: if (!ts.isFunctionBlock(n)) { var parent_7 = n.parent; var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); @@ -38865,18 +39806,18 @@ var ts; // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collaps the block, but consider its hint span // to be the entire span of the parent. - if (parent_7.kind === 197 /* DoStatement */ || - parent_7.kind === 200 /* ForInStatement */ || - parent_7.kind === 201 /* ForOfStatement */ || - parent_7.kind === 199 /* ForStatement */ || - parent_7.kind === 196 /* IfStatement */ || - parent_7.kind === 198 /* WhileStatement */ || - parent_7.kind === 205 /* WithStatement */ || - parent_7.kind === 244 /* CatchClause */) { + if (parent_7.kind === 199 /* DoStatement */ || + parent_7.kind === 202 /* ForInStatement */ || + parent_7.kind === 203 /* ForOfStatement */ || + parent_7.kind === 201 /* ForStatement */ || + parent_7.kind === 198 /* IfStatement */ || + parent_7.kind === 200 /* WhileStatement */ || + parent_7.kind === 207 /* WithStatement */ || + parent_7.kind === 246 /* CatchClause */) { addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_7.kind === 209 /* TryStatement */) { + if (parent_7.kind === 211 /* TryStatement */) { // Could be the try-block, or the finally-block. var tryStatement = parent_7; if (tryStatement.tryBlock === n) { @@ -38903,23 +39844,23 @@ var ts; break; } // Fallthrough. - case 219 /* ModuleBlock */: { + case 221 /* ModuleBlock */: { var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 165 /* ObjectLiteralExpression */: - case 220 /* CaseBlock */: { + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: + case 167 /* ObjectLiteralExpression */: + case 222 /* CaseBlock */: { var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); @@ -38949,12 +39890,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_32 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_32); + for (var name_28 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_28); 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_32); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_28); if (!matches) { continue; } @@ -38967,14 +39908,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_32); + matches = patternMatcher.getMatches(containers, name_28); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_32, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_28, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -39013,7 +39954,7 @@ var ts; containers.unshift(text); } else if (declaration.name.kind === 136 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ true); + return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); } else { // Don't know how to add this. @@ -39033,12 +39974,12 @@ var ts; } return true; } - if (expression.kind === 166 /* PropertyAccessExpression */) { + if (expression.kind === 168 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); } - return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion:*/ true); + return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); } return false; } @@ -39047,7 +39988,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. if (declaration.name.kind === 136 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ false)) { + if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -39108,7 +40049,7 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile) { + function getNavigationBarItems(sourceFile, compilerOptions) { // If the source file has any child items, then it included in the tree // and takes lexical ownership of all other top-level items. var hasGlobalNode = false; @@ -39120,17 +40061,17 @@ var ts; var current = node.parent; while (current) { switch (current.kind) { - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: // If we have a module declared as A.B.C, it is more "intuitive" // to say it only has a single layer of depth do { current = current.parent; - } while (current.kind === 218 /* ModuleDeclaration */); + } while (current.kind === 220 /* ModuleDeclaration */); // fall through - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 217 /* InterfaceDeclaration */: + case 215 /* FunctionDeclaration */: indent++; } current = current.parent; @@ -39141,21 +40082,21 @@ var ts; var childNodes = []; function visit(node) { switch (node.kind) { - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: ts.forEach(node.declarationList.declarations, visit); break; - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: + case 163 /* ObjectBindingPattern */: + case 164 /* ArrayBindingPattern */: ts.forEach(node.elements, visit); break; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -39167,7 +40108,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 226 /* NamespaceImport */) { childNodes.push(importClause.namedBindings); } else { @@ -39176,21 +40117,21 @@ var ts; } } break; - case 163 /* BindingElement */: - case 211 /* VariableDeclaration */: + case 165 /* BindingElement */: + case 213 /* VariableDeclaration */: if (ts.isBindingPattern(node.name)) { visit(node.name); break; } // Fall through - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 213 /* FunctionDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 217 /* InterfaceDeclaration */: + case 220 /* ModuleDeclaration */: + case 215 /* FunctionDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 228 /* ImportSpecifier */: + case 232 /* ExportSpecifier */: childNodes.push(node); break; } @@ -39238,17 +40179,17 @@ var ts; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { var node = nodes_4[_i]; switch (node.kind) { - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 217 /* InterfaceDeclaration */: topLevelNodes.push(node); break; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: var moduleDeclaration = node; topLevelNodes.push(node); addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); break; - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: var functionDeclaration = node; if (isTopLevelFunctionDeclaration(functionDeclaration)) { topLevelNodes.push(node); @@ -39259,12 +40200,12 @@ var ts; } } function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 213 /* FunctionDeclaration */) { + if (functionDeclaration.kind === 215 /* FunctionDeclaration */) { // A function declaration is 'top level' if it contains any function declarations // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === 192 /* Block */) { + if (functionDeclaration.body && functionDeclaration.body.kind === 194 /* Block */) { // Proper function declarations can only have identifier names - if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 213 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { + if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 215 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { return true; } // Or if it is not parented by another function. i.e all functions @@ -39341,7 +40282,7 @@ var ts; return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); case 149 /* IndexSignature */: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 247 /* EnumMember */: + case 249 /* EnumMember */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); case 147 /* CallSignature */: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); @@ -39350,18 +40291,18 @@ var ts; case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: var variableDeclarationNode; - var name_33; - if (node.kind === 163 /* BindingElement */) { - name_33 = node.name; + var name_29; + if (node.kind === 165 /* BindingElement */) { + name_29 = node.name; variableDeclarationNode = node; // binding elements are added only for variable declarations // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 211 /* VariableDeclaration */) { + while (variableDeclarationNode && variableDeclarationNode.kind !== 213 /* VariableDeclaration */) { variableDeclarationNode = variableDeclarationNode.parent; } ts.Debug.assert(variableDeclarationNode !== undefined); @@ -39369,24 +40310,24 @@ var ts; else { ts.Debug.assert(!ts.isBindingPattern(node.name)); variableDeclarationNode = node; - name_33 = node.name; + name_29 = node.name; } if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.constElement); + return createItem(node, getTextOfNode(name_29), ts.ScriptElementKind.constElement); } else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.letElement); + return createItem(node, getTextOfNode(name_29), ts.ScriptElementKind.letElement); } else { - return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.variableElement); + return createItem(node, getTextOfNode(name_29), ts.ScriptElementKind.variableElement); } case 144 /* Constructor */: return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 230 /* ExportSpecifier */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: + case 232 /* ExportSpecifier */: + case 228 /* ImportSpecifier */: + case 223 /* ImportEqualsDeclaration */: + case 225 /* ImportClause */: + case 226 /* NamespaceImport */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); } return undefined; @@ -39416,17 +40357,17 @@ var ts; } function createTopLevelItem(node) { switch (node.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: return createSourceFileItem(node); - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: return createClassItem(node); - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: return createEnumItem(node); - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return createIterfaceItem(node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return createModuleItem(node); - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: return createFunctionItem(node); } return undefined; @@ -39438,7 +40379,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 220 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -39450,7 +40391,7 @@ var ts; return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } function createFunctionItem(node) { - if (node.body && node.body.kind === 192 /* Block */) { + if (node.body && node.body.kind === 194 /* Block */) { var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } @@ -39504,13 +40445,13 @@ var ts; return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); } function getInnermostModule(node) { - while (node.body.kind === 218 /* ModuleDeclaration */) { + while (node.body.kind === 220 /* ModuleDeclaration */) { node = node.body; } return node; } function getNodeSpan(node) { - return node.kind === 248 /* SourceFile */ + return node.kind === 250 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); } @@ -39542,12 +40483,11 @@ var ts; } function createPatternMatcher(pattern) { // We'll often see the same candidate string many times when searching (For example, when - // 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 + // 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 = {}; pattern = pattern.trim(); - var fullPatternSegment = createSegment(pattern); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); return { @@ -39587,7 +40527,7 @@ var ts; // So far so good. Now break up the container for the candidate and check if all // the dotted parts match up correctly. var totalMatch = candidateMatch; - for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i--, j--) { + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { var segment = dotSeparatedSegments[i]; var containerName = candidateContainers[j]; var containerMatch = matchSegment(containerName, segment); @@ -39626,7 +40566,7 @@ var ts; if (index > 0) { // c) If the part is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring - // match. + // match. // // Note: We only have a substring match if the lowercase part is prefix match of some // word part. That way we don't match something like 'Class' when the user types 'a'. @@ -39666,8 +40606,8 @@ var ts; if (isLowercase) { // f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? // We could check every character boundary start of the candidate for the pattern. However, that's - // an m * n operation in the wost case. Instead, find the first instance of the pattern - // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to // filter the list based on a substring that starts on a capital letter and also with a lowercase one. // (Pattern: fogbar, Candidate: quuxfogbarFogBar). if (chunk.text.length < candidate.length) { @@ -39719,7 +40659,7 @@ var ts; // // c) If the word is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring - // match. + // match. // // Note: We only have a substring match if the lowercase part is prefix match of // some word part. That way we don't match something like 'Class' when the user @@ -39733,7 +40673,7 @@ var ts; // e) If the word was not entirely lowercase, then attempt a camel cased match as // well. // - // f) The word is all lower case. Is it a case insensitive substring of the candidate starting + // f) The word is all lower case. Is it a case insensitive substring of the candidate starting // on a part boundary of the candidate? // // Only if all words have some sort of match is the pattern considered matched. @@ -39783,7 +40723,7 @@ var ts; // Note: we may have more pattern parts than candidate parts. This is because multiple // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U - // and I will both match in UI. + // and I will both match in UI. var currentCandidate = 0; var currentChunkSpan = 0; var firstMatch = undefined; @@ -39812,13 +40752,13 @@ var ts; // Consider the case of matching SiUI against SimpleUIElement. The candidate parts // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to - // still keep matching pattern parts against that candidate part. + // still keep matching pattern parts against that candidate part. for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; if (gotOneMatchThisCandidate) { // We've already gotten one pattern part match in this candidate. We will // only continue trying to consumer pattern parts if the last part and this - // part are both upper case. + // part are both upper case. if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { break; @@ -39848,42 +40788,6 @@ var ts; } } ts.createPatternMatcher = createPatternMatcher; - // Helper function to compare two matches to determine which is better. Matches are first - // ordered by kind (so all prefix matches always beat all substring matches). Then, if the - // match is a camel case match, the relative weights of the match are used to determine - // which is better (with a greater weight being better). Then if the match is of the same - // type, then a case sensitive match is considered better than an insensitive one. - function patternMatchCompareTo(match1, match2) { - return compareType(match1, match2) || - compareCamelCase(match1, match2) || - compareCase(match1, match2) || - comparePunctuation(match1, match2); - } - function comparePunctuation(result1, result2) { - // Consider a match to be better if it was successful without stripping punctuation - // versus a match that had to strip punctuation to succeed. - if (result1.punctuationStripped !== result2.punctuationStripped) { - return result1.punctuationStripped ? 1 : -1; - } - return 0; - } - function compareCase(result1, result2) { - if (result1.isCaseSensitive !== result2.isCaseSensitive) { - return result1.isCaseSensitive ? -1 : 1; - } - return 0; - } - function compareType(result1, result2) { - return result1.kind - result2.kind; - } - function compareCamelCase(result1, result2) { - if (result1.kind === PatternMatchKind.camelCase && result2.kind === PatternMatchKind.camelCase) { - // Swap the values here. If result1 has a higher weight, then we want it to come - // first. - return result2.camelCaseWeight - result1.camelCaseWeight; - } - return 0; - } function createSegment(text) { return { totalTextChunk: createTextChunk(text), @@ -39902,7 +40806,7 @@ var ts; if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { return false; } - // TODO: find a way to determine this for any unicode characters in a + // TODO: find a way to determine this for any unicode characters in a // non-allocating manner. var str = String.fromCharCode(ch); return str === str.toUpperCase(); @@ -39915,19 +40819,11 @@ var ts; if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { return false; } - // TODO: find a way to determine this for any unicode characters in a + // TODO: find a way to determine this for any unicode characters in a // non-allocating manner. var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function containsUpperCaseLetter(string) { - for (var i = 0, n = string.length; i < n; i++) { - if (isUpperCaseLetter(string.charCodeAt(i))) { - return true; - } - } - return false; - } function startsWith(string, search) { for (var i = 0, n = search.length; i < n; i++) { if (string.charCodeAt(i) !== search.charCodeAt(i)) { @@ -39964,7 +40860,7 @@ var ts; if (ch < 127 /* maxAsciiCharacter */) { return ch; } - // TODO: find a way to compute this for any unicode characters in a + // TODO: find a way to compute this for any unicode characters in a // non-allocating manner. return String.fromCharCode(ch).toLowerCase().charCodeAt(0); } @@ -39982,9 +40878,10 @@ var ts; for (var i = 0; i < pattern.length; i++) { var ch = pattern.charCodeAt(i); if (isWordChar(ch)) { - if (wordLength++ === 0) { + if (wordLength === 0) { wordStart = i; } + wordLength++; } else { if (wordLength > 0) { @@ -40115,7 +41012,7 @@ var ts; var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); // See if the casing indicates we're starting a new word. Note: if we're breaking on // words, then just seeing an upper case character isn't enough. Instead, it has to - // be uppercase and the previous character can't be uppercase. + // be uppercase and the previous character can't be uppercase. // // For example, breaking "AddMetadata" on words would make: Add Metadata // @@ -40305,7 +41202,7 @@ var ts; } return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo); function createJavaScriptSignatureHelpItems(argumentInfo) { - if (argumentInfo.invocation.kind !== 168 /* CallExpression */) { + if (argumentInfo.invocation.kind !== 170 /* CallExpression */) { return undefined; } // See if we can find some symbol with the call expression name that has call signatures. @@ -40313,7 +41210,7 @@ var ts; var expression = callExpression.expression; var name = expression.kind === 69 /* Identifier */ ? expression - : expression.kind === 166 /* PropertyAccessExpression */ + : expression.kind === 168 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.text) { @@ -40346,7 +41243,7 @@ var ts; * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node) { - if (node.parent.kind === 168 /* CallExpression */ || node.parent.kind === 169 /* NewExpression */) { + if (node.parent.kind === 170 /* CallExpression */ || node.parent.kind === 171 /* NewExpression */) { var callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a sig help session @@ -40399,25 +41296,25 @@ var ts; }; } } - else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 172 /* TaggedTemplateExpression */) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0); } } - else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 172 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 185 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } - else if (node.parent.kind === 190 /* TemplateSpan */ && node.parent.parent.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.parent.kind === 192 /* TemplateSpan */ && node.parent.parent.parent.kind === 172 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 185 /* TemplateExpression */); // If we're just after a template tail, don't show signature help. if (node.kind === 14 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; @@ -40535,7 +41432,7 @@ var ts; // // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 183 /* TemplateExpression */) { + if (template.kind === 185 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -40544,7 +41441,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node) { - for (var n = node; n.kind !== 248 /* SourceFile */; n = n.parent) { + for (var n = node; n.kind !== 250 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -40744,25 +41641,25 @@ var ts; return false; } switch (n.kind) { - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 165 /* ObjectLiteralExpression */: - case 161 /* ObjectBindingPattern */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: + case 167 /* ObjectLiteralExpression */: + case 163 /* ObjectBindingPattern */: case 155 /* TypeLiteral */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 220 /* CaseBlock */: + case 194 /* Block */: + case 221 /* ModuleBlock */: + case 222 /* CaseBlock */: return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 169 /* NewExpression */: + case 171 /* NewExpression */: if (!n.arguments) { return true; } // fall through - case 168 /* CallExpression */: - case 172 /* ParenthesizedExpression */: + case 170 /* CallExpression */: + case 174 /* ParenthesizedExpression */: case 160 /* ParenthesizedType */: return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); case 152 /* FunctionType */: @@ -40771,13 +41668,13 @@ var ts; case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 148 /* ConstructSignature */: case 147 /* CallSignature */: - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -40787,19 +41684,19 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 18 /* CloseParenToken */, sourceFile); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 196 /* IfStatement */: + case 198 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 195 /* ExpressionStatement */: + case 197 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 23 /* SemicolonToken */); - case 164 /* ArrayLiteralExpression */: - case 162 /* ArrayBindingPattern */: - case 167 /* ElementAccessExpression */: + case 166 /* ArrayLiteralExpression */: + case 164 /* ArrayBindingPattern */: + case 169 /* ElementAccessExpression */: case 136 /* ComputedPropertyName */: case 157 /* TupleType */: return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); @@ -40808,16 +41705,16 @@ var ts; return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicitly always consider them non-completed return false; - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 200 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 197 /* DoStatement */: + case 199 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; var hasWhileKeyword = findChildOfKind(n, 104 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { @@ -40826,25 +41723,25 @@ var ts; return isCompletedNode(n.statement, sourceFile); case 154 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 176 /* TypeOfExpression */: - case 175 /* DeleteExpression */: - case 177 /* VoidExpression */: - case 184 /* YieldExpression */: - case 185 /* SpreadElementExpression */: + case 178 /* TypeOfExpression */: + case 177 /* DeleteExpression */: + case 179 /* VoidExpression */: + case 186 /* YieldExpression */: + case 187 /* SpreadElementExpression */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 170 /* TaggedTemplateExpression */: + case 172 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 183 /* TemplateExpression */: + case 185 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 190 /* TemplateSpan */: + case 192 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 179 /* PrefixUnaryExpression */: + case 181 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 181 /* BinaryExpression */: + case 183 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 182 /* ConditionalExpression */: + case 184 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -40900,7 +41797,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 === 271 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 273 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -41006,7 +41903,7 @@ var ts; function findPrecedingToken(position, sourceFile, startNode) { return find(startNode || sourceFile); function findRightmostToken(n) { - if (isToken(n) || n.kind === 236 /* JsxText */) { + if (isToken(n) || n.kind === 238 /* JsxText */) { return n; } var children = n.getChildren(); @@ -41014,7 +41911,7 @@ var ts; return candidate && findRightmostToken(candidate); } function find(n) { - if (isToken(n) || n.kind === 236 /* JsxText */) { + if (isToken(n) || n.kind === 238 /* JsxText */) { return n; } var children = n.getChildren(); @@ -41028,10 +41925,10 @@ var ts; // if no - position is in the node itself so we should recurse in it. // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). // if this is the case - then we should assume that token in question is located in previous child. - if (position < child.end && (nodeHasTokens(child) || child.kind === 236 /* JsxText */)) { + if (position < child.end && (nodeHasTokens(child) || child.kind === 238 /* JsxText */)) { var start = child.getStart(sourceFile); var lookInPreviousChild = (start >= position) || - (child.kind === 236 /* JsxText */ && start === child.end); // whitespace only JsxText + (child.kind === 238 /* JsxText */ && start === child.end); // whitespace only JsxText if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); @@ -41043,8 +41940,8 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 248 /* SourceFile */); - // Here we know that none of child token nodes embrace the position, + ts.Debug.assert(startNode !== undefined || n.kind === 250 /* SourceFile */); + // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' @@ -41065,7 +41962,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); - return token && token.kind === 9 /* StringLiteral */ && position > token.getStart(); + return token && (token.kind === 9 /* StringLiteral */ || token.kind === 162 /* StringLiteralType */) && position > token.getStart(); } ts.isInString = isInString; function isInComment(sourceFile, position) { @@ -41169,10 +42066,10 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 151 /* TypeReference */ || node.kind === 168 /* CallExpression */) { + if (node.kind === 151 /* TypeReference */ || node.kind === 170 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 214 /* ClassDeclaration */ || node.kind === 215 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 216 /* ClassDeclaration */ || node.kind === 217 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -41195,6 +42092,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 /* StringLiteral */ + || kind === 162 /* StringLiteralType */ || kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; @@ -41431,7 +42329,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 226 /* ImportSpecifier */ || location.parent.kind === 230 /* ExportSpecifier */) && + (location.parent.kind === 228 /* ImportSpecifier */ || location.parent.kind === 232 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -41488,6 +42386,7 @@ var ts; advance: advance, readTokenInfo: readTokenInfo, isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, close: function () { ts.Debug.assert(scanner !== undefined); @@ -41553,10 +42452,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 238 /* JsxAttribute */: - case 235 /* JsxOpeningElement */: - case 237 /* JsxClosingElement */: - case 234 /* JsxSelfClosingElement */: + case 240 /* JsxAttribute */: + case 237 /* JsxOpeningElement */: + case 239 /* JsxClosingElement */: + case 236 /* JsxSelfClosingElement */: return node.kind === 69 /* Identifier */; } } @@ -41763,7 +42662,7 @@ var ts; return false; }; return FormattingContext; - })(); + }()); formatting.FormattingContext = FormattingContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41802,7 +42701,7 @@ var ts; "flag=" + this.Flag + "]"; }; return Rule; - })(); + }()); formatting.Rule = Rule; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41849,7 +42748,7 @@ var ts; return new RuleDescriptor(left, right); }; return RuleDescriptor; - })(); + }()); formatting.RuleDescriptor = RuleDescriptor; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41891,7 +42790,7 @@ var ts; return result; }; return RuleOperation; - })(); + }()); formatting.RuleOperation = RuleOperation; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41926,7 +42825,7 @@ var ts; }; RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; - })(); + }()); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42030,6 +42929,7 @@ var ts; // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9 /* StringLiteral */, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); // Lambda expressions + this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 34 /* EqualsGreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // Optional parameters and let args this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22 /* DotDotDotToken */, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); @@ -42055,72 +42955,68 @@ var ts; this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsSameLineTokenContext), 2 /* Space */)); this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); // template string - this.SpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - 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.IsSameLineTokenContext), 8 /* Delete */)); + 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.IsSameLineTokenContext), 8 /* Delete */)); // These rules are higher in priority than user-configurable rules. - this.HighPriorityCommonRules = - [ - this.IgnoreBeforeComment, this.IgnoreAfterLineComment, - this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, - this.NoSpaceAfterQuestionMark, - this.NoSpaceBeforeDot, this.NoSpaceAfterDot, - this.NoSpaceAfterUnaryPrefixOperator, - this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, - this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, - this.SpaceAfterPostincrementWhenFollowedByAdd, - this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, - this.SpaceAfterPostdecrementWhenFollowedBySubtract, - this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, - this.NoSpaceAfterCloseBrace, - this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, - this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, - this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, - this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, - this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, - this.NoSpaceBetweenReturnAndSemicolon, - this.SpaceAfterCertainKeywords, - this.SpaceAfterLetConstInVariableDeclaration, - this.NoSpaceBeforeOpenParenInFuncCall, - this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, - this.SpaceAfterVoidOperator, - this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, - this.SpaceBetweenTagAndTemplateString, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, - // TypeScript-specific rules - this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, - this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, - this.SpaceAfterModuleName, - this.SpaceAfterArrow, - this.NoSpaceAfterEllipsis, - this.NoSpaceAfterOptionalParameters, - this.NoSpaceBetweenEmptyInterfaceBraceBrackets, - this.NoSpaceBeforeOpenAngularBracket, - this.NoSpaceBetweenCloseParenAndAngularBracket, - this.NoSpaceAfterOpenAngularBracket, - this.NoSpaceBeforeCloseAngularBracket, - this.NoSpaceAfterCloseAngularBracket, - this.NoSpaceAfterTypeAssertion, - this.SpaceBeforeAt, - this.NoSpaceAfterAt, - this.SpaceAfterDecorator, - ]; + this.HighPriorityCommonRules = [ + this.IgnoreBeforeComment, this.IgnoreAfterLineComment, + this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, + this.NoSpaceAfterQuestionMark, + this.NoSpaceBeforeDot, this.NoSpaceAfterDot, + this.NoSpaceAfterUnaryPrefixOperator, + this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, + this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, + this.SpaceAfterPostincrementWhenFollowedByAdd, + this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, + this.SpaceAfterPostdecrementWhenFollowedBySubtract, + this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, + this.NoSpaceAfterCloseBrace, + this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, + this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, + this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, + this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, + this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, + this.NoSpaceBetweenReturnAndSemicolon, + this.SpaceAfterCertainKeywords, + this.SpaceAfterLetConstInVariableDeclaration, + this.NoSpaceBeforeOpenParenInFuncCall, + this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, + this.SpaceAfterVoidOperator, + this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, + this.NoSpaceBetweenTagAndTemplateString, + // TypeScript-specific rules + this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, + this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, + this.SpaceAfterModuleName, + this.SpaceBeforeArrow, this.SpaceAfterArrow, + this.NoSpaceAfterEllipsis, + this.NoSpaceAfterOptionalParameters, + this.NoSpaceBetweenEmptyInterfaceBraceBrackets, + this.NoSpaceBeforeOpenAngularBracket, + this.NoSpaceBetweenCloseParenAndAngularBracket, + this.NoSpaceAfterOpenAngularBracket, + this.NoSpaceBeforeCloseAngularBracket, + this.NoSpaceAfterCloseAngularBracket, + this.NoSpaceAfterTypeAssertion, + this.SpaceBeforeAt, + this.NoSpaceAfterAt, + this.SpaceAfterDecorator, + ]; // These rules are lower in priority than user-configurable rules. - this.LowPriorityCommonRules = - [ - this.NoSpaceBeforeSemicolon, - this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, - this.NoSpaceBeforeComma, - this.NoSpaceBeforeOpenBracket, - this.NoSpaceAfterCloseBracket, - this.SpaceAfterSemicolon, - this.NoSpaceBeforeOpenParenInFuncDecl, - this.SpaceBetweenStatements, this.SpaceAfterTryFinally - ]; + this.LowPriorityCommonRules = [ + this.NoSpaceBeforeSemicolon, + this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, + this.NoSpaceBeforeComma, + this.NoSpaceBeforeOpenBracket, + this.NoSpaceAfterCloseBracket, + this.SpaceAfterSemicolon, + this.NoSpaceBeforeOpenParenInFuncDecl, + this.SpaceBetweenStatements, this.SpaceAfterTryFinally + ]; /// /// 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.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, 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.IsSameLineTokenContext), 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.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); @@ -42152,15 +43048,20 @@ var ts; this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenBracketToken */, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // Insert space after opening and before closing template string braces + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + 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.IsSameLineTokenContext), 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.IsSameLineTokenContext), 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 */)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_34 in o) { - if (o[name_34] === rule) { - return name_34; + for (var name_30 in o) { + if (o[name_30] === rule) { + return name_30; } } throw new Error("Unknown rule"); @@ -42169,39 +43070,39 @@ var ts; /// Contexts /// Rules.IsForContext = function (context) { - return context.contextNode.kind === 199 /* ForStatement */; + return context.contextNode.kind === 201 /* ForStatement */; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 189 /* AsExpression */: + case 183 /* BinaryExpression */: + case 184 /* ConditionalExpression */: + case 191 /* AsExpression */: case 150 /* TypePredicate */: case 158 /* UnionType */: case 159 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 163 /* BindingElement */: + case 165 /* BindingElement */: // equals in type X = ... - case 216 /* TypeAliasDeclaration */: + case 218 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: // equal in p = 0; case 138 /* Parameter */: - case 247 /* EnumMember */: + case 249 /* EnumMember */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return context.currentTokenSpan.kind === 56 /* EqualsToken */ || context.nextTokenSpan.kind === 56 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 200 /* ForInStatement */: + case 202 /* ForInStatement */: return context.currentTokenSpan.kind === 90 /* InKeyword */ || context.nextTokenSpan.kind === 90 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 201 /* ForOfStatement */: + case 203 /* ForOfStatement */: return context.currentTokenSpan.kind === 134 /* OfKeyword */ || context.nextTokenSpan.kind === 134 /* OfKeyword */; } return false; @@ -42210,7 +43111,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 182 /* ConditionalExpression */; + return context.contextNode.kind === 184 /* ConditionalExpression */; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. @@ -42254,17 +43155,17 @@ var ts; return true; } switch (node.kind) { - case 192 /* Block */: - case 220 /* CaseBlock */: - case 165 /* ObjectLiteralExpression */: - case 219 /* ModuleBlock */: + case 194 /* Block */: + case 222 /* CaseBlock */: + case 167 /* ObjectLiteralExpression */: + case 221 /* ModuleBlock */: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: //case SyntaxKind.MemberFunctionDeclaration: @@ -42272,75 +43173,75 @@ var ts; case 146 /* SetAccessor */: ///case SyntaxKind.MethodSignature: case 147 /* CallSignature */: - case 173 /* FunctionExpression */: + case 175 /* FunctionExpression */: case 144 /* Constructor */: - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: //case SyntaxKind.ConstructorDeclaration: //case SyntaxKind.SimpleArrowFunctionExpression: //case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: return true; } return false; }; Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 213 /* FunctionDeclaration */ || context.contextNode.kind === 173 /* FunctionExpression */; + return context.contextNode.kind === 215 /* FunctionDeclaration */ || context.contextNode.kind === 175 /* FunctionExpression */; }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: case 155 /* TypeLiteral */: - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 214 /* ClassDeclaration */: - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: - case 192 /* Block */: - case 244 /* CatchClause */: - case 219 /* ModuleBlock */: - case 206 /* SwitchStatement */: + case 216 /* ClassDeclaration */: + case 220 /* ModuleDeclaration */: + case 219 /* EnumDeclaration */: + case 194 /* Block */: + case 246 /* CatchClause */: + case 221 /* ModuleBlock */: + case 208 /* SwitchStatement */: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 196 /* IfStatement */: - case 206 /* SwitchStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: - case 209 /* TryStatement */: - case 197 /* DoStatement */: - case 205 /* WithStatement */: + case 198 /* IfStatement */: + case 208 /* SwitchStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 200 /* WhileStatement */: + case 211 /* TryStatement */: + case 199 /* DoStatement */: + case 207 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 244 /* CatchClause */: + case 246 /* CatchClause */: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 165 /* ObjectLiteralExpression */; + return context.contextNode.kind === 167 /* ObjectLiteralExpression */; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 168 /* CallExpression */; + return context.contextNode.kind === 170 /* CallExpression */; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 169 /* NewExpression */; + return context.contextNode.kind === 171 /* NewExpression */; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); @@ -42348,8 +43249,11 @@ var ts; Rules.IsPreviousTokenNotComma = function (context) { return context.currentTokenSpan.kind !== 24 /* CommaToken */; }; + Rules.IsNextTokenNotCloseBracket = function (context) { + return context.nextTokenSpan.kind !== 20 /* CloseBracketToken */; + }; Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 174 /* ArrowFunction */; + return context.contextNode.kind === 176 /* ArrowFunction */; }; Rules.IsSameLineTokenContext = function (context) { return context.TokensAreOnSameLine(); @@ -42370,14 +43274,14 @@ var ts; return node.kind === 139 /* Decorator */; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 212 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 214 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 218 /* ModuleDeclaration */; + return context.contextNode.kind === 220 /* ModuleDeclaration */; }; Rules.IsObjectTypeContext = function (context) { return context.contextNode.kind === 155 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; @@ -42388,20 +43292,20 @@ var ts; } switch (parent.kind) { case 151 /* TypeReference */: - case 171 /* TypeAssertionExpression */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 173 /* TypeAssertionExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 217 /* InterfaceDeclaration */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 147 /* CallSignature */: case 148 /* ConstructSignature */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 188 /* ExpressionWithTypeArguments */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: + case 190 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -42412,16 +43316,16 @@ var ts; Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 171 /* TypeAssertionExpression */; + return context.contextNode.kind === 173 /* TypeAssertionExpression */; }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 177 /* VoidExpression */; + return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 179 /* VoidExpression */; }; Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 184 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 186 /* YieldExpression */ && context.contextNode.expression !== undefined; }; return Rules; - })(); + }()); formatting.Rules = Rules; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42489,7 +43393,7 @@ var ts; return null; }; return RulesMap; - })(); + }()); formatting.RulesMap = RulesMap; var MaskBitSize = 5; var Mask = 0x1f; @@ -42541,7 +43445,7 @@ var ts; this.rulesInsertionIndexBitmap = temp; }; return RulesBucketConstructionState; - })(); + }()); formatting.RulesBucketConstructionState = RulesBucketConstructionState; var RulesBucket = (function () { function RulesBucket() { @@ -42576,7 +43480,7 @@ var ts; state.IncreaseInsertionIndex(position); }; return RulesBucket; - })(); + }()); formatting.RulesBucket = RulesBucket; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42604,7 +43508,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenRangeAccess; - })(); + }()); Shared.TokenRangeAccess = TokenRangeAccess; var TokenValuesAccess = (function () { function TokenValuesAccess(tks) { @@ -42617,7 +43521,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenValuesAccess; - })(); + }()); Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { @@ -42630,7 +43534,7 @@ var ts; return tokenValue === this.token; }; return TokenSingleValueAccess; - })(); + }()); Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { @@ -42649,7 +43553,7 @@ var ts; return "[allTokens]"; }; return TokenAllAccess; - })(); + }()); Shared.TokenAllAccess = TokenAllAccess; var TokenRange = (function () { function TokenRange(tokenAccess) { @@ -42691,7 +43595,7 @@ var ts; TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 128 /* NumberKeyword */, 130 /* StringKeyword */, 120 /* BooleanKeyword */, 131 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); return TokenRange; - })(); + }()); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -42777,6 +43681,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } + if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); + } + else { + rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); + } if (options.InsertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } @@ -42802,7 +43714,7 @@ var ts; return rules; }; return RulesProvider; - })(); + }()); formatting.RulesProvider = RulesProvider; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42903,17 +43815,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 192 /* Block */ && ts.rangeContainsRange(body.statements, node); - case 248 /* SourceFile */: - case 192 /* Block */: - case 219 /* ModuleBlock */: + return body && body.kind === 194 /* Block */ && ts.rangeContainsRange(body.statements, node); + case 250 /* SourceFile */: + case 194 /* Block */: + case 221 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -43011,17 +43923,17 @@ var ts; */ function getOwnOrInheritedDelta(n, options, sourceFile) { var previousLine = -1 /* Unknown */; - var childKind = 0 /* Unknown */; + var child; while (n) { var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; if (previousLine !== -1 /* Unknown */ && line !== previousLine) { break; } - if (formatting.SmartIndenter.shouldIndentChildNode(n.kind, childKind)) { + if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { return options.IndentSize; } previousLine = line; - childKind = n.kind; + child = n; n = n.parent; } return 0; @@ -43051,6 +43963,13 @@ var ts; var delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile); processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } + if (!formattingScanner.isOnToken()) { + var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (leadingTrivia) { + processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined); + trimTrailingWhitespacesForRemainingRange(); + } + } formattingScanner.close(); return edits; // local functions @@ -43062,7 +43981,8 @@ var ts; * to inherited indentation from its predecessors. */ function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { - if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos)) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || + ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { if (inheritedIndentation !== -1 /* Unknown */) { return inheritedIndentation; } @@ -43079,32 +43999,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - if (indentation === -1 /* Unknown */) { - if (isSomeBlock(node.kind)) { - // blocks should be indented in - // - other blocks - // - source file - // - switch\default clauses - if (isSomeBlock(parent.kind) || - parent.kind === 248 /* SourceFile */ || - parent.kind === 241 /* CaseClause */ || - parent.kind === 242 /* DefaultClause */) { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - else { - indentation = parentDynamicIndentation.getIndentation(); - } - } - else { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); - } - else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - } - } - var delta = formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -43112,7 +44007,15 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + } + else if (indentation === -1 /* Unknown */) { + if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + indentation = parentDynamicIndentation.getIndentation(); + } + else { + indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + } } return { indentation: indentation, @@ -43124,10 +44027,10 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 214 /* ClassDeclaration */: return 73 /* ClassKeyword */; - case 215 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; - case 213 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; - case 217 /* EnumDeclaration */: return 217 /* EnumDeclaration */; + case 216 /* ClassDeclaration */: return 73 /* ClassKeyword */; + case 217 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; + case 215 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; + case 219 /* EnumDeclaration */: return 219 /* EnumDeclaration */; case 145 /* GetAccessor */: return 123 /* GetKeyword */; case 146 /* SetAccessor */: return 129 /* SetKeyword */; case 143 /* MethodDeclaration */: @@ -43142,7 +44045,7 @@ var ts; } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { return { - getIndentationForComment: function (kind, tokenIndentation) { + getIndentationForComment: function (kind, tokenIndentation, container) { switch (kind) { // preceding comment to the token that closes the indentation scope inherits the indentation from the scope // .. { @@ -43151,11 +44054,11 @@ var ts; case 16 /* CloseBraceToken */: case 20 /* CloseBracketToken */: case 18 /* CloseParenToken */: - return indentation + delta; + return indentation + getEffectiveDelta(delta, container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, - getIndentationForToken: function (line, kind) { + getIndentationForToken: function (line, kind, container) { if (nodeStartLine !== line && node.decorators) { if (kind === getFirstNonDecoratorTokenOfNode(node)) { // if this token is the first token following the list of decorators, we do not need to indent @@ -43176,20 +44079,20 @@ var ts; return indentation; default: // if token line equals to the line of containing node (this is a first token in the node) - use node indentation - return nodeStartLine !== line ? indentation + delta : indentation; + return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; } }, getIndentation: function () { return indentation; }, - getDelta: function () { return delta; }, + getDelta: function (child) { return getEffectiveDelta(delta, child); }, recomputeIndentation: function (lineAdded) { - if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { indentation += options.IndentSize; } else { indentation -= options.IndentSize; } - if (formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */)) { + if (formatting.SmartIndenter.shouldIndentChildNode(node)) { delta = options.IndentSize; } else { @@ -43198,6 +44101,10 @@ var ts; } } }; + function getEffectiveDelta(delta, child) { + // Delta value should be zero when the node explicitly prevents indentation of the child node + return formatting.SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0; + } } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { @@ -43269,7 +44176,7 @@ var ts; // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules var tokenInfo = formattingScanner.readTokenInfo(child); ts.Debug.assert(tokenInfo.token.end === child.end); - consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } var effectiveParentStartLine = child.kind === 139 /* Decorator */ ? childStartLine : undecoratedParentStartLine; @@ -43323,7 +44230,7 @@ var ts; } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation) { + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; @@ -43358,10 +44265,10 @@ var ts; } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : -1 /* Unknown */; if (currentTokenInfo.leadingTrivia) { - var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation); + var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); var indentNextTokenOrTrivia = true; for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { var triviaItem = _a[_i]; @@ -43450,9 +44357,7 @@ var ts; } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line - trimTrailingWhitespaces = - (rule.Operation.Action & (4 /* NewLine */ | 2 /* Space */)) && - rule.Flag !== 1 /* CanDeleteNewLines */; + trimTrailingWhitespaces = !(rule.Operation.Action & 8 /* Delete */) && rule.Flag !== 1 /* CanDeleteNewLines */; } else { trimTrailingWhitespaces = true; @@ -43535,16 +44440,36 @@ var ts; if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { continue; } - var pos = lineEndPosition; - while (pos >= lineStartPosition && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { - pos--; - } - if (pos !== lineEndPosition) { - ts.Debug.assert(pos === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))); - recordDelete(pos + 1, lineEndPosition - pos); + var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + if (whitespaceStart !== -1) { + ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(whitespaceStart - 1))); + recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); } } } + /** + * @param start The position of the first character in range + * @param end The position of the last character in range + */ + function getTrailingWhitespaceStartPosition(start, end) { + var pos = end; + while (pos >= start && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== end) { + return pos + 1; + } + return -1; + } + /** + * Trimming will be done for lines after the previous range + */ + function trimTrailingWhitespacesForRemainingRange() { + var startPosition = previousRange ? previousRange.end : originalRange.pos; + var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); + } function newTextChange(start, len, newText) { return { span: ts.createTextSpan(start, len), newText: newText }; } @@ -43598,8 +44523,8 @@ var ts; } function isSomeBlock(kind) { switch (kind) { - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 194 /* Block */: + case 221 /* ModuleBlock */: return true; } return false; @@ -43607,11 +44532,11 @@ var ts; function getOpenTokenForList(node, list) { switch (node.kind) { case 144 /* Constructor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: if (node.typeParameters === list) { return 25 /* LessThanToken */; } @@ -43619,8 +44544,8 @@ var ts; return 17 /* OpenParenToken */; } break; - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: if (node.typeArguments === list) { return 25 /* LessThanToken */; } @@ -43744,7 +44669,7 @@ var ts; var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); } - if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 181 /* BinaryExpression */) { + if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 183 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -43758,7 +44683,7 @@ var ts; var currentStart; var indentationDelta; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current.kind, previous ? previous.kind : 0 /* Unknown */)) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) { currentStart = getStartLineAndCharacterForNode(current, sourceFile); if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) { indentationDelta = 0; @@ -43825,7 +44750,7 @@ var ts; } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line - if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) { + if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { indentationDelta += options.IndentSize; } current = parent; @@ -43863,7 +44788,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && - (parent.kind === 248 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 250 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -43896,7 +44821,7 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 196 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 198 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 80 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -43914,13 +44839,13 @@ var ts; return node.parent.typeArguments; } break; - case 165 /* ObjectLiteralExpression */: + case 167 /* ObjectLiteralExpression */: return node.parent.properties; - case 164 /* ArrayLiteralExpression */: + case 166 /* ArrayLiteralExpression */: return node.parent.elements; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 147 /* CallSignature */: @@ -43935,8 +44860,8 @@ var ts; } break; } - case 169 /* NewExpression */: - case 168 /* CallExpression */: { + case 171 /* NewExpression */: + case 170 /* CallExpression */: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -43966,8 +44891,8 @@ var ts; if (node.kind === 18 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 168 /* CallExpression */ || - node.parent.kind === 169 /* NewExpression */) && + if (node.parent && (node.parent.kind === 170 /* CallExpression */ || + node.parent.kind === 171 /* NewExpression */) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); @@ -43985,10 +44910,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: + case 168 /* PropertyAccessExpression */: + case 169 /* ElementAccessExpression */: node = node.expression; break; default: @@ -44052,34 +44977,35 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 195 /* ExpressionStatement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 164 /* ArrayLiteralExpression */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 165 /* ObjectLiteralExpression */: + case 197 /* ExpressionStatement */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 166 /* ArrayLiteralExpression */: + case 194 /* Block */: + case 221 /* ModuleBlock */: + case 167 /* ObjectLiteralExpression */: case 155 /* TypeLiteral */: case 157 /* TupleType */: - case 220 /* CaseBlock */: - case 242 /* DefaultClause */: - case 241 /* CaseClause */: - case 172 /* ParenthesizedExpression */: - case 166 /* PropertyAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 193 /* VariableStatement */: - case 211 /* VariableDeclaration */: - case 227 /* ExportAssignment */: - case 204 /* ReturnStatement */: - case 182 /* ConditionalExpression */: - case 162 /* ArrayBindingPattern */: - case 161 /* ObjectBindingPattern */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: + case 222 /* CaseBlock */: + case 244 /* DefaultClause */: + case 243 /* CaseClause */: + case 174 /* ParenthesizedExpression */: + case 168 /* PropertyAccessExpression */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: + case 195 /* VariableStatement */: + case 213 /* VariableDeclaration */: + case 229 /* ExportAssignment */: + case 206 /* ReturnStatement */: + case 184 /* ConditionalExpression */: + case 164 /* ArrayBindingPattern */: + case 163 /* ObjectBindingPattern */: + case 237 /* JsxOpeningElement */: + case 236 /* JsxSelfClosingElement */: + case 242 /* JsxExpression */: case 142 /* MethodSignature */: case 147 /* CallSignature */: case 148 /* ConstructSignature */: @@ -44087,34 +45013,43 @@ var ts; case 152 /* FunctionType */: case 153 /* ConstructorType */: case 160 /* ParenthesizedType */: - case 170 /* TaggedTemplateExpression */: - case 178 /* AwaitExpression */: + case 172 /* TaggedTemplateExpression */: + case 180 /* AwaitExpression */: + case 227 /* NamedImports */: return true; } return false; } - function shouldIndentChildNode(parent, child) { - if (nodeContentIsAlwaysIndented(parent)) { - return true; - } - switch (parent) { - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 196 /* IfStatement */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + /* @internal */ + function nodeWillIndentChild(parent, child, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { + case 199 /* DoStatement */: + case 200 /* WhileStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 201 /* ForStatement */: + case 198 /* IfStatement */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 143 /* MethodDeclaration */: - case 174 /* ArrowFunction */: + case 176 /* ArrowFunction */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - return child !== 192 /* Block */; - default: - return false; + return childKind !== 194 /* Block */; + case 235 /* JsxElement */: + return childKind !== 239 /* JsxClosingElement */; } + // No explicit rule for given nodes so the result will follow the default value argument + return indentByDefault; + } + SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; + /* + Function returns true when the parent node should indent the given child by an explicit rule + */ + function shouldIndentChildNode(parent, child) { + return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); @@ -44157,7 +45092,7 @@ var ts; return undefined; }; return StringScriptSnapshot; - })(); + }()); function fromString(text) { return new StringScriptSnapshot(text); } @@ -44256,7 +45191,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(271 /* SyntaxList */, nodes.pos, nodes.end, 2048 /* Synthetic */, this); + var list = createNode(273 /* SyntaxList */, nodes.pos, nodes.end, 2048 /* Synthetic */, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -44333,7 +45268,7 @@ var ts; return child.kind < 135 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; return NodeObject; - })(); + }()); var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -44355,7 +45290,7 @@ var ts; return this.documentationComment; }; return SymbolObject; - })(); + }()); function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { var documentationComment = []; var docComments = getJsDocCommentsSeparatedByNewLines(); @@ -44373,7 +45308,7 @@ var ts; // Make sure we are collecting doc comment from declaration once, // In case of union property there might be same declaration multiple times // which only varies in type parameter - // Eg. let a: Array | Array; a.length + // Eg. const a: Array | Array; a.length // The property length will have two declarations of property length coming // from Array - Array and Array if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { @@ -44388,15 +45323,15 @@ var ts; }); } // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 218 /* ModuleDeclaration */ && declaration.body.kind === 218 /* ModuleDeclaration */) { + if (declaration.kind === 220 /* ModuleDeclaration */ && declaration.body.kind === 220 /* ModuleDeclaration */) { return; } // If this is dotted module name, get the doc comments from the parent - while (declaration.kind === 218 /* ModuleDeclaration */ && declaration.parent.kind === 218 /* ModuleDeclaration */) { + while (declaration.kind === 220 /* ModuleDeclaration */ && declaration.parent.kind === 220 /* ModuleDeclaration */) { declaration = declaration.parent; } // Get the cleaned js doc comment text from the declaration - ts.forEach(getJsDocCommentTextRange(declaration.kind === 211 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { + ts.forEach(getJsDocCommentTextRange(declaration.kind === 213 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedJsDocComment) { ts.addRange(jsDocCommentParts, cleanedJsDocComment); @@ -44444,7 +45379,8 @@ var ts; } function pushDocCommentLineText(docComments, text, blankLineCount) { // Add the empty lines in between texts - while (blankLineCount--) { + while (blankLineCount) { + blankLineCount--; docComments.push(ts.textPart("")); } docComments.push(ts.textPart(text)); @@ -44670,7 +45606,7 @@ var ts; : undefined; }; return TypeObject; - })(); + }()); var SignatureObject = (function () { function SignatureObject(checker) { this.checker = checker; @@ -44696,7 +45632,7 @@ var ts; return this.documentationComment; }; return SignatureObject; - })(); + }()); var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { @@ -44742,7 +45678,7 @@ var ts; } if (declaration.name.kind === 136 /* ComputedPropertyName */) { var expr = declaration.name.expression; - if (expr.kind === 166 /* PropertyAccessExpression */) { + if (expr.kind === 168 /* PropertyAccessExpression */) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -44762,7 +45698,7 @@ var ts; } function visit(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: var functionDeclaration = node; @@ -44784,31 +45720,31 @@ var ts; ts.forEachChild(node, visit); } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: - case 218 /* ModuleDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 230 /* ExportSpecifier */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 218 /* TypeAliasDeclaration */: + case 219 /* EnumDeclaration */: + case 220 /* ModuleDeclaration */: + case 223 /* ImportEqualsDeclaration */: + case 232 /* ExportSpecifier */: + case 228 /* ImportSpecifier */: + case 223 /* ImportEqualsDeclaration */: + case 225 /* ImportClause */: + case 226 /* NamespaceImport */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 155 /* TypeLiteral */: addDeclaration(node); // fall through case 144 /* Constructor */: - case 193 /* VariableStatement */: - case 212 /* VariableDeclarationList */: - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 219 /* ModuleBlock */: + case 195 /* VariableStatement */: + case 214 /* VariableDeclarationList */: + case 163 /* ObjectBindingPattern */: + case 164 /* ArrayBindingPattern */: + case 221 /* ModuleBlock */: ts.forEachChild(node, visit); break; - case 192 /* Block */: + case 194 /* Block */: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } @@ -44819,25 +45755,25 @@ var ts; break; } // fall through - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); break; } - case 247 /* EnumMember */: + case 249 /* EnumMember */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: addDeclaration(node); break; - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -44849,7 +45785,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 226 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -44862,12 +45798,12 @@ var ts; } }; return SourceFileObject; - })(NodeObject); + }(NodeObject)); var TextChange = (function () { function TextChange() { } return TextChange; - })(); + }()); ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { @@ -44957,7 +45893,7 @@ var ts; // enum E ScriptElementKind.enumElement = "enum"; // Inside module and script only - // let v = .. + // const v = .. ScriptElementKind.variableElement = "var"; // Inside function ScriptElementKind.localVariableElement = "local var"; @@ -45026,7 +45962,7 @@ var ts; ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; return ClassificationTypeNames; - })(); + }()); ts.ClassificationTypeNames = ClassificationTypeNames; (function (ClassificationType) { ClassificationType[ClassificationType["comment"] = 1] = "comment"; @@ -45065,16 +46001,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 173 /* FunctionExpression */) { + if (declaration.kind === 175 /* FunctionExpression */) { return true; } - if (declaration.kind !== 211 /* VariableDeclaration */ && declaration.kind !== 213 /* FunctionDeclaration */) { + if (declaration.kind !== 213 /* VariableDeclaration */ && declaration.kind !== 215 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent_8 = declaration.parent; !ts.isFunctionBlock(parent_8); parent_8 = parent_8.parent) { // Reached source file or module block - if (parent_8.kind === 248 /* SourceFile */ || parent_8.kind === 219 /* ModuleBlock */) { + if (parent_8.kind === 250 /* SourceFile */ || parent_8.kind === 221 /* ModuleBlock */) { return false; } } @@ -45157,7 +46093,7 @@ var ts; return file && file.scriptSnapshot; }; return HostCache; - })(); + }()); var SyntaxTreeCache = (function () { function SyntaxTreeCache(host) { this.host = host; @@ -45172,7 +46108,7 @@ var ts; var sourceFile; if (this.currentFileName !== fileName) { // This is a new file, just parse it - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents:*/ true); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents*/ true); } else if (this.currentFileVersion !== version) { // This is the same file, just a newer version. Incrementally parse the file. @@ -45189,7 +46125,7 @@ var ts; return this.currentSourceFile; }; return SyntaxTreeCache; - })(); + }()); function setSourceFileFields(sourceFile, scriptSnapshot, version) { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; @@ -45234,7 +46170,7 @@ var ts; sourceMapText = text; } else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name); + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); outputText = text; } }, @@ -45244,7 +46180,8 @@ var ts; getCurrentDirectory: function () { return ""; }, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; } + readFile: function (fileName) { return ""; }, + directoryExists: function (directoryExists) { return true; } }; var program = ts.createProgram([inputFileName], options, compilerHost); var diagnostics; @@ -45326,7 +46263,7 @@ var ts; } } // Otherwise, just create a new source file. - return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents:*/ true); + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; function createGetCanonicalFileName(useCaseSensitivefileNames) { @@ -45342,7 +46279,7 @@ var ts; var buckets = {}; var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx; + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + +"|" + settings.allowJs; } function getBucketForCompilationSettings(settings, createIfMissing) { var key = getKeyFromCompilationSettings(settings); @@ -45353,7 +46290,7 @@ var ts; return bucket; } function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = ts.lookUp(buckets, name); var sourceFiles = []; entries.forEachValue(function (key, entry) { @@ -45369,13 +46306,13 @@ var ts; sourceFiles: sourceFiles }; }); - return JSON.stringify(bucketInfoArray, null, 2); + return JSON.stringify(bucketInfoArray, undefined, 2); } function acquireDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ true); + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring*/ true); } function updateDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ false); + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring*/ false); } function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); @@ -45384,7 +46321,7 @@ var ts; if (!entry) { ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents:*/ false); + var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false); entry = { sourceFile: sourceFile, languageServiceRefCount: 0, @@ -45411,7 +46348,7 @@ var ts; return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { - var bucket = getBucketForCompilationSettings(compilationSettings, false); + var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ false); ts.Debug.assert(bucket !== undefined); var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = bucket.get(path); @@ -45507,7 +46444,7 @@ var ts; } } else if (token === 56 /* EqualsToken */) { - if (tryConsumeRequireCall(/* skipCurrentToken */ true)) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } @@ -45599,7 +46536,7 @@ var ts; if (token === 69 /* Identifier */ || ts.isKeyword(token)) { token = scanner.scan(); if (token === 56 /* EqualsToken */) { - if (tryConsumeRequireCall(/* skipCurrentToken */ true)) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { return true; } } @@ -45686,7 +46623,7 @@ var ts; if (tryConsumeDeclare() || tryConsumeImport() || tryConsumeExport() || - (detectJavaScriptImports && (tryConsumeRequireCall(/* skipCurrentToken */ false) || tryConsumeDefine()))) { + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { continue; } else { @@ -45705,7 +46642,7 @@ var ts; /// Helpers function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 207 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 209 /* LabeledStatement */ && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -45714,12 +46651,12 @@ var ts; } function isJumpStatementTarget(node) { return node.kind === 69 /* Identifier */ && - (node.parent.kind === 203 /* BreakStatement */ || node.parent.kind === 202 /* ContinueStatement */) && + (node.parent.kind === 205 /* BreakStatement */ || node.parent.kind === 204 /* ContinueStatement */) && node.parent.label === node; } function isLabelOfLabeledStatement(node) { return node.kind === 69 /* Identifier */ && - node.parent.kind === 207 /* LabeledStatement */ && + node.parent.kind === 209 /* LabeledStatement */ && node.parent.label === node; } /** @@ -45727,7 +46664,7 @@ var ts; * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 207 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 209 /* LabeledStatement */; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -45741,22 +46678,22 @@ var ts; return node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node; } function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 168 /* PropertyAccessExpression */ && node.parent.name === node; } function isCallExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 168 /* CallExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 170 /* CallExpression */ && node.parent.expression === node; } function isNewExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 169 /* NewExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 171 /* NewExpression */ && node.parent.expression === node; } function isNameOfModuleDeclaration(node) { - return node.parent.kind === 218 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 220 /* ModuleDeclaration */ && node.parent.name === node; } function isNameOfFunctionDeclaration(node) { return node.kind === 69 /* Identifier */ && @@ -45765,22 +46702,22 @@ var ts; /** Returns true if node is a name of an object literal property, e.g. "a" in x = { "a": 1 } */ function isNameOfPropertyAssignment(node) { return (node.kind === 69 /* Identifier */ || node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - (node.parent.kind === 245 /* PropertyAssignment */ || node.parent.kind === 246 /* ShorthandPropertyAssignment */) && node.parent.name === node; + (node.parent.kind === 247 /* PropertyAssignment */ || node.parent.kind === 248 /* ShorthandPropertyAssignment */) && node.parent.name === node; } function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { switch (node.parent.kind) { case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 247 /* EnumMember */: + case 247 /* PropertyAssignment */: + case 249 /* EnumMember */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: return node.parent.name === node; - case 167 /* ElementAccessExpression */: + case 169 /* ElementAccessExpression */: return node.parent.argumentExpression === node; } } @@ -45854,17 +46791,17 @@ var ts; return undefined; } switch (node.kind) { - case 248 /* SourceFile */: + case 250 /* SourceFile */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 218 /* ModuleDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 219 /* EnumDeclaration */: + case 220 /* ModuleDeclaration */: return node; } } @@ -45872,18 +46809,18 @@ var ts; ts.getContainerNode = getContainerNode; /* @internal */ function getNodeKind(node) { switch (node.kind) { - case 218 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; - case 214 /* ClassDeclaration */: return ScriptElementKind.classElement; - case 215 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; - case 216 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; - case 217 /* EnumDeclaration */: return ScriptElementKind.enumElement; - case 211 /* VariableDeclaration */: + case 220 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; + case 216 /* ClassDeclaration */: return ScriptElementKind.classElement; + case 217 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; + case 218 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; + case 219 /* EnumDeclaration */: return ScriptElementKind.enumElement; + case 213 /* VariableDeclaration */: return ts.isConst(node) ? ScriptElementKind.constElement : ts.isLet(node) ? ScriptElementKind.letElement : ScriptElementKind.variableElement; - case 213 /* FunctionDeclaration */: return ScriptElementKind.functionElement; + case 215 /* FunctionDeclaration */: return ScriptElementKind.functionElement; case 145 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; case 146 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; case 143 /* MethodDeclaration */: @@ -45897,13 +46834,13 @@ var ts; case 147 /* CallSignature */: return ScriptElementKind.callSignatureElement; case 144 /* Constructor */: return ScriptElementKind.constructorImplementationElement; case 137 /* TypeParameter */: return ScriptElementKind.typeParameterElement; - case 247 /* EnumMember */: return ScriptElementKind.variableElement; + case 249 /* EnumMember */: return ScriptElementKind.variableElement; case 138 /* Parameter */: return (node.flags & 56 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 223 /* ImportClause */: - case 230 /* ExportSpecifier */: - case 224 /* NamespaceImport */: + case 223 /* ImportEqualsDeclaration */: + case 228 /* ImportSpecifier */: + case 225 /* ImportClause */: + case 232 /* ExportSpecifier */: + case 226 /* NamespaceImport */: return ScriptElementKind.alias; } return ScriptElementKind.unknown; @@ -45922,7 +46859,7 @@ var ts; } }; return CancellationTokenObject; - })(); + }()); function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -45985,7 +46922,8 @@ var ts; (oldSettings.target !== newSettings.target || oldSettings.module !== newSettings.module || oldSettings.noResolve !== newSettings.noResolve || - oldSettings.jsx !== newSettings.jsx); + oldSettings.jsx !== newSettings.jsx || + oldSettings.allowJs !== newSettings.allowJs); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -46005,6 +46943,10 @@ var ts; // stub missing host functionality var entry = hostCache.getOrCreateEntry(fileName); return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + }, + directoryExists: function (directoryName) { + ts.Debug.assert(!host.resolveModuleNames); + return ts.directoryProbablyExists(directoryName, host); } }; if (host.resolveModuleNames) { @@ -46074,8 +47016,11 @@ var ts; return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); } function sourceFileUpToDate(sourceFile) { + if (!sourceFile) { + return false; + } var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); - return sourceFile && sourceFile.version === hostCache.getVersion(path); + return sourceFile.version === hostCache.getVersion(path); } function programUpToDate() { // If we haven't create a program yet, then it is not up-to-date @@ -46124,12 +47069,6 @@ var ts; function getSemanticDiagnostics(fileName) { synchronizeHostData(); var targetSourceFile = getValidSourceFile(fileName); - // For JavaScript files, we don't want to report the normal typescript semantic errors. - // Instead, we just report errors for using TypeScript-only constructs from within a - // JavaScript file. - if (ts.isSourceFileJavaScript(targetSourceFile)) { - return getJavaScriptSemanticDiagnostics(targetSourceFile); - } // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); @@ -46140,151 +47079,6 @@ var ts; var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return ts.concatenate(semanticDiagnostics, declarationDiagnostics); } - function getJavaScriptSemanticDiagnostics(sourceFile) { - var diagnostics = []; - walk(sourceFile); - return diagnostics; - function walk(node) { - if (!node) { - return false; - } - switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case 227 /* ExportAssignment */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; - case 214 /* ClassDeclaration */: - var classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case 243 /* HeritageClause */: - var heritageClause = node; - if (heritageClause.token === 106 /* ImplementsKeyword */) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 215 /* InterfaceDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 218 /* ModuleDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 216 /* TypeAliasDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: - case 213 /* FunctionDeclaration */: - var functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; - } - break; - case 193 /* VariableStatement */: - var variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; - case 211 /* VariableDeclaration */: - var variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; - } - break; - case 168 /* CallExpression */: - case 169 /* NewExpression */: - var expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - 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 138 /* Parameter */: - var parameter = node; - if (parameter.modifiers) { - 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) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, '?')); - return true; - } - if (parameter.type) { - diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 141 /* PropertyDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 217 /* EnumDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 171 /* TypeAssertionExpression */: - var typeAssertionExpression = node; - diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); - return true; - case 139 /* Decorator */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); - return true; - } - return ts.forEachChild(node, walk); - } - function checkTypeParameters(typeParameters) { - if (typeParameters) { - 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; - } - function checkTypeAnnotation(type) { - if (type) { - diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkModifiers(modifiers) { - if (modifiers) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 122 /* DeclareKeyword */: - diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - return true; - // These are all legal modifiers. - case 113 /* StaticKeyword */: - case 82 /* ExportKeyword */: - case 74 /* ConstKeyword */: - case 77 /* DefaultKeyword */: - case 115 /* AbstractKeyword */: - } - } - } - return false; - } - } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); @@ -46301,7 +47095,7 @@ var ts; // First check of the displayName is not external module; if it is an external module, it is not valid entry if ((symbol.flags & 1536 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { // If the symbol is external module, don't show it in the completion list - // (i.e declare module "http" { let x; } | // <= request completion here, "http" should not be there) + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } @@ -46324,20 +47118,14 @@ var ts; // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks) { - if (!ts.isIdentifierStart(name.charCodeAt(0), target)) { + if (!ts.isIdentifier(name, target)) { return undefined; } - for (var i = 1, n = name.length; i < n; i++) { - if (!ts.isIdentifierPart(name.charCodeAt(i), target)) { - return undefined; - } - } } return name; } function getCompletionData(fileName, position) { var typeChecker = program.getTypeChecker(); - var syntacticStart = new Date().getTime(); var sourceFile = getValidSourceFile(fileName); var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var isJsDocTagName = false; @@ -46349,7 +47137,7 @@ var ts; var insideComment = isInsideComment(sourceFile, currentToken, position); log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); if (insideComment) { - // The current position is next to the '@' sign, when no tag name being provided yet. + // The current position is next to the '@' sign, when no tag name being provided yet. // Provide a full list of tag names if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { isJsDocTagName = true; @@ -46364,9 +47152,9 @@ var ts; isJsDocTagName = true; } switch (tag.kind) { - case 269 /* JSDocTypeTag */: - case 267 /* JSDocParameterTag */: - case 268 /* JSDocReturnTag */: + case 271 /* JSDocTypeTag */: + case 269 /* JSDocParameterTag */: + case 270 /* JSDocReturnTag */: var tagWithExpression = tag; if (tagWithExpression.typeExpression) { insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; @@ -46378,7 +47166,7 @@ var ts; return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { - // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); return undefined; @@ -46393,9 +47181,9 @@ var ts; // 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_3 = new Date().getTime(); + var start_6 = new Date().getTime(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_3)); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_6)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -46413,7 +47201,7 @@ var ts; } var parent_9 = contextToken.parent, kind = contextToken.kind; if (kind === 21 /* DotToken */) { - if (parent_9.kind === 166 /* PropertyAccessExpression */) { + if (parent_9.kind === 168 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } @@ -46432,7 +47220,7 @@ var ts; isRightOfOpenTag = true; location = contextToken; } - else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 237 /* JsxClosingElement */) { + else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 239 /* JsxClosingElement */) { isStartingCloseTag = true; } } @@ -46475,7 +47263,7 @@ var ts; // Right of dot member completion list isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */) { + if (node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 168 /* PropertyAccessExpression */) { var symbol = typeChecker.getSymbolAtLocation(node); // This is an alias, follow what it aliases if (symbol && symbol.flags & 8388608 /* Alias */) { @@ -46531,7 +47319,7 @@ var ts; } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType; - if ((jsxContainer.kind === 234 /* JsxSelfClosingElement */) || (jsxContainer.kind === 235 /* JsxOpeningElement */)) { + if ((jsxContainer.kind === 236 /* JsxSelfClosingElement */) || (jsxContainer.kind === 237 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { @@ -46603,15 +47391,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 236 /* JsxText */) { + if (contextToken.kind === 238 /* JsxText */) { return true; } if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 235 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 237 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 237 /* JsxClosingElement */ || contextToken.parent.kind === 234 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 233 /* JsxElement */; + if (contextToken.parent.kind === 239 /* JsxClosingElement */ || contextToken.parent.kind === 236 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 235 /* JsxElement */; } } return false; @@ -46621,36 +47409,36 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 24 /* CommaToken */: - return containingNodeKind === 168 /* CallExpression */ // func( a, | + return containingNodeKind === 170 /* CallExpression */ // func( a, | || containingNodeKind === 144 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 169 /* NewExpression */ // new C(a, | - || containingNodeKind === 164 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 181 /* BinaryExpression */ // let x = (a, | + || containingNodeKind === 171 /* NewExpression */ // new C(a, | + || containingNodeKind === 166 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 183 /* BinaryExpression */ // const x = (a, | || containingNodeKind === 152 /* FunctionType */; // var x: (s: string, list| case 17 /* OpenParenToken */: - return containingNodeKind === 168 /* CallExpression */ // func( | + return containingNodeKind === 170 /* CallExpression */ // func( | || containingNodeKind === 144 /* Constructor */ // constructor( | - || containingNodeKind === 169 /* NewExpression */ // new C(a| - || containingNodeKind === 172 /* ParenthesizedExpression */ // let x = (a| + || containingNodeKind === 171 /* NewExpression */ // new C(a| + || containingNodeKind === 174 /* ParenthesizedExpression */ // const x = (a| || containingNodeKind === 160 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 19 /* OpenBracketToken */: - return containingNodeKind === 164 /* ArrayLiteralExpression */ // [ | + return containingNodeKind === 166 /* ArrayLiteralExpression */ // [ | || containingNodeKind === 149 /* IndexSignature */ // [ | : string ] || containingNodeKind === 136 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 125 /* ModuleKeyword */: // module | case 126 /* NamespaceKeyword */: return true; case 21 /* DotToken */: - return containingNodeKind === 218 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 220 /* ModuleDeclaration */; // module A.| case 15 /* OpenBraceToken */: - return containingNodeKind === 214 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 216 /* ClassDeclaration */; // class A{ | case 56 /* EqualsToken */: - return containingNodeKind === 211 /* VariableDeclaration */ // let x = a| - || containingNodeKind === 181 /* BinaryExpression */; // x = a| + return containingNodeKind === 213 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 183 /* BinaryExpression */; // x = a| case 12 /* TemplateHead */: - return containingNodeKind === 183 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 185 /* TemplateExpression */; // `aa ${| case 13 /* TemplateMiddle */: - return containingNodeKind === 190 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 192 /* TemplateSpan */; // `aa ${10} dd ${| case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: @@ -46668,15 +47456,16 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 /* StringLiteral */ + || contextToken.kind === 162 /* StringLiteralType */ || contextToken.kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_4 = contextToken.getStart(); + var start_7 = 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_4 < position && position < end) { + if (start_7 < position && position < end) { return true; } if (position === end) { @@ -46697,14 +47486,14 @@ var ts; isMemberCompletion = true; var typeForObject; var existingMembers; - if (objectLikeContainer.kind === 165 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 167 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; typeForObject = typeChecker.getContextualType(objectLikeContainer); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 161 /* ObjectBindingPattern */) { + else if (objectLikeContainer.kind === 163 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -46750,9 +47539,9 @@ var ts; * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 225 /* NamedImports */ ? - 222 /* ImportDeclaration */ : - 228 /* ExportDeclaration */; + var declarationKind = namedImportsOrExports.kind === 227 /* NamedImports */ ? + 224 /* ImportDeclaration */ : + 230 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -46775,10 +47564,10 @@ var ts; function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // let x = { | + case 15 /* OpenBraceToken */: // const x = { | case 24 /* CommaToken */: var parent_10 = contextToken.parent; - if (parent_10 && (parent_10.kind === 165 /* ObjectLiteralExpression */ || parent_10.kind === 161 /* ObjectBindingPattern */)) { + if (parent_10 && (parent_10.kind === 167 /* ObjectLiteralExpression */ || parent_10.kind === 163 /* ObjectBindingPattern */)) { return parent_10; } break; @@ -46796,8 +47585,8 @@ var ts; case 15 /* OpenBraceToken */: // import { | case 24 /* CommaToken */: switch (contextToken.parent.kind) { - case 225 /* NamedImports */: - case 229 /* NamedExports */: + case 227 /* NamedImports */: + case 231 /* NamedExports */: return contextToken.parent; } } @@ -46811,12 +47600,12 @@ var ts; case 26 /* LessThanSlashToken */: case 39 /* SlashToken */: case 69 /* Identifier */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - if (parent_11 && (parent_11.kind === 234 /* JsxSelfClosingElement */ || parent_11.kind === 235 /* JsxOpeningElement */)) { + case 240 /* JsxAttribute */: + case 241 /* JsxSpreadAttribute */: + if (parent_11 && (parent_11.kind === 236 /* JsxSelfClosingElement */ || parent_11.kind === 237 /* JsxOpeningElement */)) { return parent_11; } - else if (parent_11.kind === 238 /* JsxAttribute */) { + else if (parent_11.kind === 240 /* JsxAttribute */) { return parent_11.parent; } break; @@ -46824,18 +47613,18 @@ var ts; // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 9 /* StringLiteral */: - if (parent_11 && ((parent_11.kind === 238 /* JsxAttribute */) || (parent_11.kind === 239 /* JsxSpreadAttribute */))) { + if (parent_11 && ((parent_11.kind === 240 /* JsxAttribute */) || (parent_11.kind === 241 /* JsxSpreadAttribute */))) { return parent_11.parent; } break; case 16 /* CloseBraceToken */: if (parent_11 && - parent_11.kind === 240 /* JsxExpression */ && + parent_11.kind === 242 /* JsxExpression */ && parent_11.parent && - (parent_11.parent.kind === 238 /* JsxAttribute */)) { + (parent_11.parent.kind === 240 /* JsxAttribute */)) { return parent_11.parent.parent; } - if (parent_11 && parent_11.kind === 239 /* JsxSpreadAttribute */) { + if (parent_11 && parent_11.kind === 241 /* JsxSpreadAttribute */) { return parent_11.parent; } break; @@ -46845,9 +47634,9 @@ var ts; } function isFunction(kind) { switch (kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 213 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: @@ -46866,54 +47655,54 @@ var ts; var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 24 /* CommaToken */: - return containingNodeKind === 211 /* VariableDeclaration */ || - containingNodeKind === 212 /* VariableDeclarationList */ || - containingNodeKind === 193 /* VariableStatement */ || - containingNodeKind === 217 /* EnumDeclaration */ || + return containingNodeKind === 213 /* VariableDeclaration */ || + containingNodeKind === 214 /* VariableDeclarationList */ || + containingNodeKind === 195 /* VariableStatement */ || + containingNodeKind === 219 /* EnumDeclaration */ || isFunction(containingNodeKind) || - containingNodeKind === 214 /* ClassDeclaration */ || - containingNodeKind === 186 /* ClassExpression */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 162 /* ArrayBindingPattern */ || - containingNodeKind === 216 /* TypeAliasDeclaration */; // type Map, K, | + containingNodeKind === 216 /* ClassDeclaration */ || + containingNodeKind === 188 /* ClassExpression */ || + containingNodeKind === 217 /* InterfaceDeclaration */ || + containingNodeKind === 164 /* ArrayBindingPattern */ || + containingNodeKind === 218 /* TypeAliasDeclaration */; // type Map, K, | case 21 /* DotToken */: - return containingNodeKind === 162 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 164 /* ArrayBindingPattern */; // var [.| case 54 /* ColonToken */: - return containingNodeKind === 163 /* BindingElement */; // var {x :html| + return containingNodeKind === 165 /* BindingElement */; // var {x :html| case 19 /* OpenBracketToken */: - return containingNodeKind === 162 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 164 /* ArrayBindingPattern */; // var [x| case 17 /* OpenParenToken */: - return containingNodeKind === 244 /* CatchClause */ || + return containingNodeKind === 246 /* CatchClause */ || isFunction(containingNodeKind); case 15 /* OpenBraceToken */: - return containingNodeKind === 217 /* EnumDeclaration */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 155 /* TypeLiteral */; // let x : { | + return containingNodeKind === 219 /* EnumDeclaration */ || + containingNodeKind === 217 /* InterfaceDeclaration */ || + containingNodeKind === 155 /* TypeLiteral */; // const x : { | case 23 /* SemicolonToken */: return containingNodeKind === 140 /* PropertySignature */ && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 215 /* InterfaceDeclaration */ || - contextToken.parent.parent.kind === 155 /* TypeLiteral */); // let x : { a; | + (contextToken.parent.parent.kind === 217 /* InterfaceDeclaration */ || + contextToken.parent.parent.kind === 155 /* TypeLiteral */); // const x : { a; | case 25 /* LessThanToken */: - return containingNodeKind === 214 /* ClassDeclaration */ || - containingNodeKind === 186 /* ClassExpression */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 216 /* TypeAliasDeclaration */ || + return containingNodeKind === 216 /* ClassDeclaration */ || + containingNodeKind === 188 /* ClassExpression */ || + containingNodeKind === 217 /* InterfaceDeclaration */ || + containingNodeKind === 218 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); case 113 /* StaticKeyword */: return containingNodeKind === 141 /* PropertyDeclaration */; case 22 /* DotDotDotToken */: return containingNodeKind === 138 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 162 /* ArrayBindingPattern */); // var [...z| + contextToken.parent.parent.kind === 164 /* ArrayBindingPattern */); // var [...z| case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: return containingNodeKind === 138 /* Parameter */; case 116 /* AsKeyword */: - return containingNodeKind === 226 /* ImportSpecifier */ || - containingNodeKind === 230 /* ExportSpecifier */ || - containingNodeKind === 224 /* NamespaceImport */; + return containingNodeKind === 228 /* ImportSpecifier */ || + containingNodeKind === 232 /* ExportSpecifier */ || + containingNodeKind === 226 /* NamespaceImport */; case 73 /* ClassKeyword */: case 81 /* EnumKeyword */: case 107 /* InterfaceKeyword */: @@ -46973,8 +47762,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_35 = element.propertyName || element.name; - exisingImportsOrExports[name_35.text] = true; + var name_31 = element.propertyName || element.name; + exisingImportsOrExports[name_31.text] = true; } if (ts.isEmpty(exisingImportsOrExports)) { return exportsOfModule; @@ -46995,9 +47784,10 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 245 /* PropertyAssignment */ && - m.kind !== 246 /* ShorthandPropertyAssignment */ && - m.kind !== 163 /* BindingElement */) { + if (m.kind !== 247 /* PropertyAssignment */ && + m.kind !== 248 /* ShorthandPropertyAssignment */ && + m.kind !== 165 /* BindingElement */ && + m.kind !== 143 /* MethodDeclaration */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -47005,7 +47795,7 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 163 /* BindingElement */ && m.propertyName) { + if (m.kind === 165 /* BindingElement */ && m.propertyName) { // include only identifiers in completion list if (m.propertyName.kind === 69 /* Identifier */) { existingName = m.propertyName.text; @@ -47035,7 +47825,7 @@ var ts; if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } - if (attr.kind === 238 /* JsxAttribute */) { + if (attr.kind === 240 /* JsxAttribute */) { seenNames[attr.name.text] = true; } } @@ -47074,10 +47864,10 @@ var ts; var entries = []; var target = program.getCompilerOptions().target; var nameTable = getNameTable(sourceFile); - for (var name_36 in nameTable) { - if (!uniqueNames[name_36]) { - uniqueNames[name_36] = name_36; - var displayName = getCompletionEntryDisplayName(name_36, target, /*performCharacterChecks:*/ true); + for (var name_32 in nameTable) { + if (!uniqueNames[name_32]) { + uniqueNames[name_32] = name_32; + var displayName = getCompletionEntryDisplayName(name_32, target, /*performCharacterChecks*/ true); if (displayName) { var entry = { name: displayName, @@ -47105,7 +47895,7 @@ var ts; // Try to get a valid display name for this symbol, if we could not find one, then ignore it. // We would like to only show things that can be added after a dot, so for instance numeric properties can // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks:*/ true, location); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks*/ true, location); if (!displayName) { return undefined; } @@ -47154,7 +47944,7 @@ var ts; // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks:*/ false, location_2) === entryName ? s : undefined; }); + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); if (symbol) { var _a = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location_2, location_2, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; return { @@ -47183,7 +47973,7 @@ var ts; function getSymbolKind(symbol, location) { var flags = symbol.getFlags(); if (flags & 32 /* Class */) - return ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 188 /* ClassExpression */) ? ScriptElementKind.localClassElement : ScriptElementKind.classElement; if (flags & 384 /* Enum */) return ScriptElementKind.enumElement; @@ -47248,7 +48038,7 @@ var ts; }); if (!unionPropertyKind) { // If this was union of all methods, - //make sure it has call signatures before we can label it as method + // make sure it has call signatures before we can label it as method var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (typeOfUnionProperty.getCallSignatures().length) { return ScriptElementKind.memberFunctionElement; @@ -47285,7 +48075,7 @@ var ts; var signature; type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 166 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 168 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -47294,7 +48084,7 @@ var ts; } // try get the call/construct signature from the type if it matches var callExpression; - if (location.kind === 168 /* CallExpression */ || location.kind === 169 /* NewExpression */) { + if (location.kind === 170 /* CallExpression */ || location.kind === 171 /* NewExpression */) { callExpression = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { @@ -47307,7 +48097,7 @@ var ts; // Use the first candidate: signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 169 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; + var useConstructSignatures = callExpression.kind === 171 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain @@ -47341,16 +48131,16 @@ var ts; case ScriptElementKind.parameterElement: case ScriptElementKind.localVariableElement: // If it is call or construct signature of lambda's write type name - displayParts.push(ts.punctuationPart(ts.SyntaxKind.ColonToken)); + displayParts.push(ts.punctuationPart(54 /* ColonToken */)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { - displayParts.push(ts.keywordPart(ts.SyntaxKind.NewKeyword)); + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - if (!(type.flags & ts.TypeFlags.Anonymous)) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, ts.SymbolFormatFlags.WriteTypeParametersOrArguments)); + if (!(type.flags & 65536 /* Anonymous */)) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); } - addSignatureDisplayParts(signature, allSignatures, ts.TypeFormatFlags.WriteArrowStyleSignature); + addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); break; default: // Just signature @@ -47386,7 +48176,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo) { - if (ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 188 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -47430,7 +48220,7 @@ var ts; } if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 218 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 220 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -47453,35 +48243,37 @@ var ts; } else { // Method/function type parameter - var container = ts.getContainingFunction(location); - if (container) { - var signatureDeclaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).parent; - var signature = typeChecker.getSignatureFromDeclaration(signatureDeclaration); - if (signatureDeclaration.kind === 148 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + var declaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */); + ts.Debug.assert(declaration !== undefined); + declaration = declaration.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); + if (declaration.kind === 148 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 147 /* CallSignature */ && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + } + else { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path + displayParts.push(ts.keywordPart(132 /* TypeKeyword */)); displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } - else if (signatureDeclaration.kind !== 147 /* CallSignature */ && signatureDeclaration.name) { - addFullSymbolName(signatureDeclaration.symbol); - } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); - } - else { - // Type aliash type parameter - // For example - // type list = T[]; // Both T will go through same code path - var declaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).parent; - displayParts.push(ts.keywordPart(132 /* TypeKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(declaration.symbol); - writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } } } if (symbolFlags & 8 /* EnumMember */) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 247 /* EnumMember */) { + if (declaration.kind === 249 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -47497,7 +48289,7 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 221 /* ImportEqualsDeclaration */) { + if (declaration.kind === 223 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -47630,9 +48422,10 @@ var ts; // Try getting just type at this position and show switch (node.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: case 135 /* QualifiedName */: case 97 /* ThisKeyword */: + case 161 /* ThisType */: case 95 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); @@ -47712,7 +48505,7 @@ var ts; var definition; ts.forEach(signatureDeclarations, function (d) { if ((selectConstructors && d.kind === 144 /* Constructor */) || - (!selectConstructors && (d.kind === 213 /* FunctionDeclaration */ || d.kind === 143 /* MethodDeclaration */ || d.kind === 142 /* MethodSignature */))) { + (!selectConstructors && (d.kind === 215 /* FunctionDeclaration */ || d.kind === 143 /* MethodDeclaration */ || d.kind === 142 /* MethodSignature */))) { declarations.push(d); if (d.body) definition = d; @@ -47781,7 +48574,7 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 246 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 248 /* ShorthandPropertyAssignment */) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; @@ -47857,10 +48650,11 @@ var ts; function getSemanticDocumentHighlights(node) { if (node.kind === 69 /* Identifier */ || node.kind === 97 /* ThisKeyword */ || + node.kind === 161 /* ThisType */ || node.kind === 95 /* SuperKeyword */ || isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) { - var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings*/ false, /*findInComments*/ false); return convertReferencedSymbols(referencedSymbols); } return undefined; @@ -47910,58 +48704,58 @@ var ts; switch (node.kind) { case 88 /* IfKeyword */: case 80 /* ElseKeyword */: - if (hasKind(node.parent, 196 /* IfStatement */)) { + if (hasKind(node.parent, 198 /* IfStatement */)) { return getIfElseOccurrences(node.parent); } break; case 94 /* ReturnKeyword */: - if (hasKind(node.parent, 204 /* ReturnStatement */)) { + if (hasKind(node.parent, 206 /* ReturnStatement */)) { return getReturnOccurrences(node.parent); } break; case 98 /* ThrowKeyword */: - if (hasKind(node.parent, 208 /* ThrowStatement */)) { + if (hasKind(node.parent, 210 /* ThrowStatement */)) { return getThrowOccurrences(node.parent); } break; case 72 /* CatchKeyword */: - if (hasKind(parent(parent(node)), 209 /* TryStatement */)) { + if (hasKind(parent(parent(node)), 211 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; case 100 /* TryKeyword */: case 85 /* FinallyKeyword */: - if (hasKind(parent(node), 209 /* TryStatement */)) { + if (hasKind(parent(node), 211 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent); } break; case 96 /* SwitchKeyword */: - if (hasKind(node.parent, 206 /* SwitchStatement */)) { + if (hasKind(node.parent, 208 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent); } break; case 71 /* CaseKeyword */: case 77 /* DefaultKeyword */: - if (hasKind(parent(parent(parent(node))), 206 /* SwitchStatement */)) { + if (hasKind(parent(parent(parent(node))), 208 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); } break; case 70 /* BreakKeyword */: case 75 /* ContinueKeyword */: - if (hasKind(node.parent, 203 /* BreakStatement */) || hasKind(node.parent, 202 /* ContinueStatement */)) { + if (hasKind(node.parent, 205 /* BreakStatement */) || hasKind(node.parent, 204 /* ContinueStatement */)) { return getBreakOrContinueStatementOccurrences(node.parent); } break; case 86 /* ForKeyword */: - if (hasKind(node.parent, 199 /* ForStatement */) || - hasKind(node.parent, 200 /* ForInStatement */) || - hasKind(node.parent, 201 /* ForOfStatement */)) { + if (hasKind(node.parent, 201 /* ForStatement */) || + hasKind(node.parent, 202 /* ForInStatement */) || + hasKind(node.parent, 203 /* ForOfStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 104 /* WhileKeyword */: case 79 /* DoKeyword */: - if (hasKind(node.parent, 198 /* WhileStatement */) || hasKind(node.parent, 197 /* DoStatement */)) { + if (hasKind(node.parent, 200 /* WhileStatement */) || hasKind(node.parent, 199 /* DoStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; @@ -47977,8 +48771,8 @@ var ts; } break; default: - if (ts.isModifier(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 193 /* VariableStatement */)) { + if (ts.isModifierKind(node.kind) && node.parent && + (ts.isDeclaration(node.parent) || node.parent.kind === 195 /* VariableStatement */)) { return getModifierOccurrences(node.kind, node.parent); } } @@ -47994,10 +48788,10 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 208 /* ThrowStatement */) { + if (node.kind === 210 /* ThrowStatement */) { statementAccumulator.push(node); } - else if (node.kind === 209 /* TryStatement */) { + else if (node.kind === 211 /* TryStatement */) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -48025,12 +48819,12 @@ var ts; var child = throwStatement; while (child.parent) { var parent_12 = child.parent; - if (ts.isFunctionBlock(parent_12) || parent_12.kind === 248 /* SourceFile */) { + if (ts.isFunctionBlock(parent_12) || parent_12.kind === 250 /* SourceFile */) { return parent_12; } // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. - if (parent_12.kind === 209 /* TryStatement */) { + if (parent_12.kind === 211 /* TryStatement */) { var tryStatement = parent_12; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; @@ -48045,7 +48839,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 203 /* BreakStatement */ || node.kind === 202 /* ContinueStatement */) { + if (node.kind === 205 /* BreakStatement */ || node.kind === 204 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -48060,16 +48854,16 @@ var ts; function getBreakOrContinueOwner(statement) { for (var node_2 = statement.parent; node_2; node_2 = node_2.parent) { switch (node_2.kind) { - case 206 /* SwitchStatement */: - if (statement.kind === 202 /* ContinueStatement */) { + case 208 /* SwitchStatement */: + if (statement.kind === 204 /* ContinueStatement */) { continue; } // Fall through. - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: - case 197 /* DoStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 200 /* WhileStatement */: + case 199 /* DoStatement */: if (!statement.label || isLabeledBy(node_2, statement.label.text)) { return node_2; } @@ -48088,24 +48882,24 @@ var ts; var container = declaration.parent; // Make sure we only highlight the keyword when it makes sense to do so. if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 214 /* ClassDeclaration */ || - container.kind === 186 /* ClassExpression */ || + if (!(container.kind === 216 /* ClassDeclaration */ || + container.kind === 188 /* ClassExpression */ || (declaration.kind === 138 /* Parameter */ && hasKind(container, 144 /* Constructor */)))) { return undefined; } } else if (modifier === 113 /* StaticKeyword */) { - if (!(container.kind === 214 /* ClassDeclaration */ || container.kind === 186 /* ClassExpression */)) { + if (!(container.kind === 216 /* ClassDeclaration */ || container.kind === 188 /* ClassExpression */)) { return undefined; } } else if (modifier === 82 /* ExportKeyword */ || modifier === 122 /* DeclareKeyword */) { - if (!(container.kind === 219 /* ModuleBlock */ || container.kind === 248 /* SourceFile */)) { + if (!(container.kind === 221 /* ModuleBlock */ || container.kind === 250 /* SourceFile */)) { return undefined; } } else if (modifier === 115 /* AbstractKeyword */) { - if (!(container.kind === 214 /* ClassDeclaration */ || declaration.kind === 214 /* ClassDeclaration */)) { + if (!(container.kind === 216 /* ClassDeclaration */ || declaration.kind === 216 /* ClassDeclaration */)) { return undefined; } } @@ -48117,8 +48911,8 @@ var ts; var modifierFlag = getFlagFromModifier(modifier); var nodes; switch (container.kind) { - case 219 /* ModuleBlock */: - case 248 /* SourceFile */: + case 221 /* ModuleBlock */: + case 250 /* SourceFile */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */) { nodes = declaration.members.concat(declaration); @@ -48130,8 +48924,8 @@ var ts; case 144 /* Constructor */: nodes = container.parameters.concat(container.parent.members); break; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 216 /* ClassDeclaration */: + case 188 /* ClassExpression */: nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -48214,7 +49008,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86 /* ForKeyword */, 104 /* WhileKeyword */, 79 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 197 /* DoStatement */) { + if (loopNode.kind === 199 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { @@ -48235,13 +49029,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: + case 201 /* ForStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: + case 199 /* DoStatement */: + case 200 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -48295,7 +49089,7 @@ var ts; function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); // If we didn't find a containing function with a block body, bail out. - if (!(func && hasKind(func.body, 192 /* Block */))) { + if (!(func && hasKind(func.body, 194 /* Block */))) { return undefined; } var keywords = []; @@ -48311,7 +49105,7 @@ var ts; function getIfElseOccurrences(ifStatement) { var keywords = []; // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 196 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 198 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. @@ -48324,7 +49118,7 @@ var ts; break; } } - if (!hasKind(ifStatement.elseStatement, 196 /* IfStatement */)) { + if (!hasKind(ifStatement.elseStatement, 198 /* IfStatement */)) { break; } ifStatement = ifStatement.elseStatement; @@ -48400,11 +49194,11 @@ var ts; return convertReferences(referencedSymbols); } function getReferencesAtPosition(fileName, position) { - var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); return convertReferences(referencedSymbols); } function findReferences(fileName, position) { - var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); // Only include referenced symbols that have a valid definition. return ts.filter(referencedSymbols, function (rs) { return !!rs.definition; }); } @@ -48417,8 +49211,8 @@ var ts; } if (node.kind !== 69 /* Identifier */ && // TODO (drosen): This should be enabled in a later release - currently breaks rename. - //node.kind !== SyntaxKind.ThisKeyword && - //node.kind !== SyntaxKind.SuperKeyword && + // node.kind !== SyntaxKind.ThisKeyword && + // node.kind !== SyntaxKind.SuperKeyword && !isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && !isNameOfExternalModuleImportOrDeclaration(node)) { return undefined; @@ -48441,7 +49235,7 @@ var ts; return getLabelReferencesInNode(node.parent, node); } } - if (node.kind === 97 /* ThisKeyword */) { + if (node.kind === 97 /* ThisKeyword */ || node.kind === 161 /* ThisType */) { return getReferencesForThisKeyword(node, sourceFiles); } if (node.kind === 95 /* SuperKeyword */) { @@ -48475,8 +49269,8 @@ var ts; } else { var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); if (ts.lookUp(nameTable, internedName)) { @@ -48504,7 +49298,7 @@ var ts; } function isImportOrExportSpecifierImportSymbol(symbol) { return (symbol.flags & 8388608 /* Alias */) && ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 230 /* ExportSpecifier */; + return declaration.kind === 228 /* ImportSpecifier */ || declaration.kind === 232 /* ExportSpecifier */; }); } function getInternedName(symbol, location, declarations) { @@ -48531,14 +49325,14 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 173 /* FunctionExpression */ || valueDeclaration.kind === 186 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 175 /* FunctionExpression */ || valueDeclaration.kind === 188 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16 /* Private */) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 214 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 216 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. @@ -48551,7 +49345,7 @@ var ts; if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } - var scope = undefined; + var scope; var declarations = symbol.getDeclarations(); if (declarations) { for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { @@ -48564,7 +49358,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + if (container.kind === 250 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -48730,7 +49524,7 @@ var ts; } } function getReferencesForSuperKeyword(superKeyword) { - var searchSpaceNode = ts.getSuperContainer(superKeyword, /*includeFunctions*/ false); + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); if (!searchSpaceNode) { return undefined; } @@ -48759,7 +49553,7 @@ var ts; if (!node || node.kind !== 95 /* SuperKeyword */) { return; } - var container = ts.getSuperContainer(node, /*includeFunctions*/ false); + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); // If we have a 'super' container, we must have an enclosing class. // Now make sure the owning class is the same as the search-space // and has the same static qualifier as the original 'super's owner. @@ -48789,13 +49583,13 @@ var ts; staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 248 /* SourceFile */: + case 250 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // Fall through - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. @@ -48804,7 +49598,7 @@ var ts; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 248 /* SourceFile */) { + if (searchSpaceNode.kind === 250 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -48830,13 +49624,13 @@ var ts; ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 97 /* ThisKeyword */) { + if (!node || (node.kind !== 97 /* ThisKeyword */ && node.kind !== 161 /* ThisType */)) { return; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } @@ -48847,16 +49641,16 @@ var ts; result.push(getReferenceEntryFromNode(node)); } break; - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: + case 188 /* ClassExpression */: + case 216 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 64 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 248 /* SourceFile */: - if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + case 250 /* SourceFile */: + if (container.kind === 250 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -48883,8 +49677,8 @@ var ts; * property name and variable declaration of the identifier. * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service * should show both 'name' in 'obj' and 'name' in variable declaration - * let name = "Foo"; - * let obj = { name }; + * const name = "Foo"; + * const obj = { name }; * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. @@ -48894,6 +49688,14 @@ var ts; result.push(shorthandValueSymbol); } } + // If the symbol.valueDeclaration is a property parameter declaration, + // we should include both parameter declaration symbol and property declaration symbol + // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in contructor.locals. + // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 138 /* Parameter */ && + ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); + } // If this is a union property, add all the symbols from all its source symbols in all unioned types. // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { @@ -48910,11 +49712,11 @@ var ts; function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { if (symbol && symbol.flags & (32 /* Class */ | 64 /* Interface */)) { ts.forEach(symbol.getDeclarations(), function (declaration) { - if (declaration.kind === 214 /* ClassDeclaration */) { + if (declaration.kind === 216 /* ClassDeclaration */) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 215 /* InterfaceDeclaration */) { + else if (declaration.kind === 217 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -48975,19 +49777,19 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_37 = node.text; + var name_33 = node.text; if (contextualType) { if (contextualType.flags & 16384 /* Union */) { // This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types) // if not, search the constituent types for the property - var unionProperty = contextualType.getProperty(name_37); + var unionProperty = contextualType.getProperty(name_33); if (unionProperty) { return [unionProperty]; } else { var result_4 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_37); + var symbol = t.getProperty(name_33); if (symbol) { result_4.push(symbol); } @@ -48996,7 +49798,7 @@ var ts; } } else { - var symbol_1 = contextualType.getProperty(name_37); + var symbol_1 = contextualType.getProperty(name_33); if (symbol_1) { return [symbol_1]; } @@ -49054,10 +49856,10 @@ var ts; } var parent = node.parent; if (parent) { - if (parent.kind === 180 /* PostfixUnaryExpression */ || parent.kind === 179 /* PrefixUnaryExpression */) { + if (parent.kind === 182 /* PostfixUnaryExpression */ || parent.kind === 181 /* PrefixUnaryExpression */) { return true; } - else if (parent.kind === 181 /* BinaryExpression */ && parent.left === node) { + else if (parent.kind === 183 /* BinaryExpression */ && parent.left === node) { var operator = parent.operatorToken.kind; return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; } @@ -49069,9 +49871,6 @@ var ts; synchronizeHostData(); return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount); } - function containErrors(diagnostics) { - return ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); - } function getEmitOutput(fileName) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -49092,32 +49891,32 @@ var ts; function getMeaningFromDeclaration(node) { switch (node.kind) { case 138 /* Parameter */: - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 213 /* VariableDeclaration */: + case 165 /* BindingElement */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 246 /* ShorthandPropertyAssignment */: - case 247 /* EnumMember */: + case 247 /* PropertyAssignment */: + case 248 /* ShorthandPropertyAssignment */: + case 249 /* EnumMember */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 144 /* Constructor */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 244 /* CatchClause */: + case 215 /* FunctionDeclaration */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: + case 246 /* CatchClause */: return 1 /* Value */; case 137 /* TypeParameter */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: + case 217 /* InterfaceDeclaration */: + case 218 /* TypeAliasDeclaration */: case 155 /* TypeLiteral */: return 2 /* Type */; - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: if (node.name.kind === 9 /* StringLiteral */) { return 4 /* Namespace */ | 1 /* Value */; } @@ -49127,15 +49926,15 @@ var ts; else { return 4 /* Namespace */; } - case 225 /* NamedImports */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 222 /* ImportDeclaration */: - case 227 /* ExportAssignment */: - case 228 /* ExportDeclaration */: + case 227 /* NamedImports */: + case 228 /* ImportSpecifier */: + case 223 /* ImportEqualsDeclaration */: + case 224 /* ImportDeclaration */: + case 229 /* ExportAssignment */: + case 230 /* ExportDeclaration */: return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; // An external module can be a Value - case 248 /* SourceFile */: + case 250 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; @@ -49145,8 +49944,9 @@ var ts; node = node.parent; } return node.parent.kind === 151 /* TypeReference */ || - (node.parent.kind === 188 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node); + (node.parent.kind === 190 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node)) || + node.kind === 161 /* ThisType */; } function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); @@ -49154,16 +49954,16 @@ var ts; function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 166 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 166 /* PropertyAccessExpression */) { + if (root.parent.kind === 168 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 168 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 188 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 243 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 190 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 245 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 214 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || - (decl.kind === 215 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); + return (decl.kind === 216 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || + (decl.kind === 217 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); } return false; } @@ -49191,13 +49991,13 @@ var ts; // import a = |b.c|.d; // Namespace if (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 221 /* ImportEqualsDeclaration */) { + node.parent.parent.kind === 223 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; } function getMeaningFromLocation(node) { - if (node.parent.kind === 227 /* ExportAssignment */) { + if (node.parent.kind === 229 /* ExportAssignment */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } else if (isInRightSideOfImport(node)) { @@ -49237,14 +50037,16 @@ var ts; return; } switch (node.kind) { - case 166 /* PropertyAccessExpression */: + case 168 /* PropertyAccessExpression */: case 135 /* QualifiedName */: case 9 /* StringLiteral */: + case 162 /* StringLiteralType */: case 84 /* FalseKeyword */: case 99 /* TrueKeyword */: case 93 /* NullKeyword */: case 95 /* SuperKeyword */: case 97 /* ThisKeyword */: + case 161 /* ThisType */: case 69 /* Identifier */: break; // Cant create the text span @@ -49261,7 +50063,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 218 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 220 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -49285,7 +50087,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -49302,10 +50104,10 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 220 /* ModuleDeclaration */: + case 216 /* ClassDeclaration */: + case 217 /* InterfaceDeclaration */: + case 215 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -49359,7 +50161,7 @@ var ts; */ function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 218 /* ModuleDeclaration */ && + return declaration.kind === 220 /* ModuleDeclaration */ && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; }); } @@ -49433,8 +50235,8 @@ var ts; var spanStart = span.start; var spanLength = span.length; // Make a scanner we can get trivia from. - var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; @@ -49517,16 +50319,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); pos = tag.tagName.end; switch (tag.kind) { - case 267 /* JSDocParameterTag */: + case 269 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 270 /* JSDocTemplateTag */: + case 272 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 269 /* JSDocTypeTag */: + case 271 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 268 /* JSDocReturnTag */: + case 270 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -49617,16 +50419,16 @@ var ts; if (token) { if (tokenKind === 56 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 211 /* VariableDeclaration */ || + if (token.parent.kind === 213 /* VariableDeclaration */ || token.parent.kind === 141 /* PropertyDeclaration */ || token.parent.kind === 138 /* Parameter */) { return 5 /* operator */; } } - if (token.parent.kind === 181 /* BinaryExpression */ || - token.parent.kind === 179 /* PrefixUnaryExpression */ || - token.parent.kind === 180 /* PostfixUnaryExpression */ || - token.parent.kind === 182 /* ConditionalExpression */) { + if (token.parent.kind === 183 /* BinaryExpression */ || + token.parent.kind === 181 /* PrefixUnaryExpression */ || + token.parent.kind === 182 /* PostfixUnaryExpression */ || + token.parent.kind === 184 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -49635,7 +50437,7 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */) { + else if (tokenKind === 9 /* StringLiteral */ || tokenKind === 162 /* StringLiteralType */) { return 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { @@ -49649,7 +50451,7 @@ var ts; else if (tokenKind === 69 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } @@ -49659,17 +50461,17 @@ var ts; return 15 /* typeParameterName */; } return; - case 215 /* InterfaceDeclaration */: + case 217 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } @@ -49679,17 +50481,17 @@ var ts; return 17 /* parameterName */; } return; - case 235 /* JsxOpeningElement */: + case 237 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } return; - case 237 /* JsxClosingElement */: + case 239 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } return; - case 234 /* JsxSelfClosingElement */: + case 236 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } @@ -49818,7 +50620,6 @@ var ts; * be performed. */ function getDocCommentTemplateAtPosition(fileName, position) { - var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Check if in a context where we don't want to perform any insertion if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { @@ -49837,19 +50638,19 @@ var ts; var commentOwner; findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 144 /* Constructor */: - case 214 /* ClassDeclaration */: - case 193 /* VariableStatement */: + case 216 /* ClassDeclaration */: + case 195 /* VariableStatement */: break findOwner; - case 248 /* SourceFile */: + case 250 /* SourceFile */: return undefined; - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - if (commentOwner.parent.kind === 218 /* ModuleDeclaration */) { + if (commentOwner.parent.kind === 220 /* ModuleDeclaration */) { return undefined; } break findOwner; @@ -49891,7 +50692,7 @@ var ts; if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } - if (commentOwner.kind === 193 /* VariableStatement */) { + if (commentOwner.kind === 195 /* VariableStatement */) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { @@ -49909,14 +50710,14 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 172 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 174 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return rightHandSide.parameters; - case 186 /* ClassExpression */: + case 188 /* ClassExpression */: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; if (member.kind === 144 /* Constructor */) { @@ -50065,12 +50866,17 @@ var ts; if (declarations && declarations.length > 0) { // Disallow rename for elements that are defined in the standard TypeScript library. var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); + var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); if (defaultLibFileName) { for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { var current = declarations_10[_i]; var sourceFile_2 = current.getSourceFile(); + // TODO (drosen): When is there no source file? + if (!sourceFile_2) { + continue; + } var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); - if (sourceFile_2 && getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { + if (canonicalName === canonicalDefaultLibName) { return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); } } @@ -50080,10 +50886,10 @@ var ts; if (kind) { return { canRename: true, - localizedErrorMessage: undefined, - displayName: displayName, - fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kind: kind, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kindModifiers: getSymbolModifiers(symbol), triggerSpan: ts.createTextSpan(node.getStart(), node.getWidth()) }; @@ -50168,7 +50974,7 @@ var ts; // then we want 'something' to be in the name table. Similarly, if we have // "a['propname']" then we want to store "propname" in the name table. if (ts.isDeclarationName(node) || - node.parent.kind === 232 /* ExternalModuleReference */ || + node.parent.kind === 234 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node)) { nameTable[node.text] = node.text; } @@ -50181,7 +50987,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 167 /* ElementAccessExpression */ && + node.parent.kind === 169 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /// Classifier @@ -50310,7 +51116,7 @@ var ts; // (and a newline). That way when we lex we'll think we're still in a multiline comment. switch (lexState) { case 3 /* InDoubleQuoteStringLiteral */: - text = '"\\\n' + text; + text = "\"\\\n" + text; offset = 3; break; case 2 /* InSingleQuoteStringLiteral */: @@ -50440,7 +51246,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */ || token === 162 /* StringLiteralType */) { // Check to see if we finished up on a multiline string literal. var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { @@ -50579,6 +51385,7 @@ var ts; case 8 /* NumericLiteral */: return 4 /* numericLiteral */; case 9 /* StringLiteral */: + case 162 /* StringLiteralType */: return 6 /* stringLiteral */; case 10 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; @@ -50645,7 +51452,7 @@ var ts; } var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) { + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line // eg: let x =10; |--- cursor is here // let y = 10; @@ -50664,14 +51471,20 @@ var ts; // Get the span in the node based on its syntax return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - return ts.createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd()); + var start = startNode.decorators ? + ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + startNode.getStart(sourceFile); + return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { - if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { return spanInNode(node); } return spanInNode(otherwiseOnNode); } + function spanInNodeArray(nodeArray) { + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } @@ -50681,125 +51494,131 @@ var ts; function spanInNode(node) { if (node) { if (ts.isExpression(node)) { - if (node.parent.kind === 197 /* DoStatement */) { + if (node.parent.kind === 199 /* DoStatement */) { // Set span as if on while keyword return spanInPreviousNode(node); } - if (node.parent.kind === 199 /* ForStatement */) { + if (node.parent.kind === 139 /* Decorator */) { + // Set breakpoint on the decorator emit + return spanInNode(node.parent); + } + if (node.parent.kind === 201 /* ForStatement */) { // For now lets set the span on this expression, fix it later return textSpan(node); } - if (node.parent.kind === 181 /* BinaryExpression */ && node.parent.operatorToken.kind === 24 /* CommaToken */) { + if (node.parent.kind === 183 /* BinaryExpression */ && node.parent.operatorToken.kind === 24 /* CommaToken */) { // if this is comma expression, the breakpoint is possible in this expression return textSpan(node); } - if (node.parent.kind === 174 /* ArrowFunction */ && node.parent.body === node) { + if (node.parent.kind === 176 /* ArrowFunction */ && node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); } } switch (node.kind) { - case 193 /* VariableStatement */: + case 195 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 211 /* VariableDeclaration */: + case 213 /* VariableDeclaration */: case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: return spanInVariableDeclaration(node); case 138 /* Parameter */: return spanInParameterDeclaration(node); - case 213 /* FunctionDeclaration */: + case 215 /* FunctionDeclaration */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 144 /* Constructor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 176 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 192 /* Block */: + case 194 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // Fall through - case 219 /* ModuleBlock */: + case 221 /* ModuleBlock */: return spanInBlock(node); - case 244 /* CatchClause */: + case 246 /* CatchClause */: return spanInBlock(node.block); - case 195 /* ExpressionStatement */: + case 197 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 204 /* ReturnStatement */: + case 206 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 198 /* WhileStatement */: + case 200 /* WhileStatement */: // Span on while(...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 197 /* DoStatement */: + case 199 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 210 /* DebuggerStatement */: + case 212 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 196 /* IfStatement */: + case 198 /* IfStatement */: // set on if(..) span return textSpan(node, ts.findNextToken(node.expression, node)); - case 207 /* LabeledStatement */: + case 209 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: + case 205 /* BreakStatement */: + case 204 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 199 /* ForStatement */: + case 201 /* ForStatement */: return spanInForStatement(node); - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: // span on for (a in ...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 206 /* SwitchStatement */: + case 208 /* SwitchStatement */: // span on switch(...) return textSpan(node, ts.findNextToken(node.expression, node)); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 243 /* CaseClause */: + case 244 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 209 /* TryStatement */: + case 211 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 208 /* ThrowStatement */: + case 210 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 227 /* ExportAssignment */: + case 229 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 222 /* ImportDeclaration */: + case 224 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 228 /* ExportDeclaration */: + case 230 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 216 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 249 /* EnumMember */: + case 170 /* CallExpression */: + case 171 /* NewExpression */: // span on complete node return textSpan(node); - case 205 /* WithStatement */: + case 207 /* WithStatement */: // span in statement return spanInNode(node.statement); + case 139 /* Decorator */: + return spanInNodeArray(node.parent.decorators); // No breakpoint in interface, type alias - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: + case 217 /* InterfaceDeclaration */: + case 218 /* TypeAliasDeclaration */: return undefined; // Tokens: case 23 /* SemicolonToken */: @@ -50829,11 +51648,11 @@ var ts; return spanInNextNode(node); default: // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 245 /* PropertyAssignment */ && node.parent.name === node) { + if (node.parent.kind === 247 /* PropertyAssignment */ && node.parent.name === node) { return spanInNode(node.parent.initializer); } // Breakpoint in type assertion goes to its operand - if (node.parent.kind === 171 /* TypeAssertionExpression */ && node.parent.type === node) { + if (node.parent.kind === 173 /* TypeAssertionExpression */ && node.parent.type === node) { return spanInNode(node.parent.expression); } // return type of function go to previous token @@ -50846,12 +51665,12 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 200 /* ForInStatement */ || - variableDeclaration.parent.parent.kind === 201 /* ForOfStatement */) { + if (variableDeclaration.parent.parent.kind === 202 /* ForInStatement */ || + variableDeclaration.parent.parent.kind === 203 /* ForOfStatement */) { return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.parent.kind === 193 /* VariableStatement */; - var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 199 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); + var isParentVariableStatement = variableDeclaration.parent.parent.kind === 195 /* VariableStatement */; + var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 201 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); var declarations = isParentVariableStatement ? variableDeclaration.parent.parent.declarationList.declarations : isDeclarationOfForStatement @@ -50905,7 +51724,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return !!(functionDeclaration.flags & 2 /* Export */) || - (functionDeclaration.parent.kind === 214 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */); + (functionDeclaration.parent.kind === 216 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -50928,18 +51747,18 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 218 /* ModuleDeclaration */: + case 220 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement - case 198 /* WhileStatement */: - case 196 /* IfStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 200 /* WhileStatement */: + case 198 /* IfStatement */: + case 202 /* ForInStatement */: + case 203 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 199 /* ForStatement */: + case 201 /* ForStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement @@ -50947,7 +51766,7 @@ var ts; } function spanInForStatement(forStatement) { if (forStatement.initializer) { - if (forStatement.initializer.kind === 212 /* VariableDeclarationList */) { + if (forStatement.initializer.kind === 214 /* VariableDeclarationList */) { var variableDeclarationList = forStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); @@ -50967,13 +51786,13 @@ var ts; // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 217 /* EnumDeclaration */: + case 219 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 214 /* ClassDeclaration */: + case 216 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 220 /* CaseBlock */: + case 222 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -50981,24 +51800,24 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 219 /* ModuleBlock */: + case 221 /* ModuleBlock */: // If this is not instantiated module block no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } - case 217 /* EnumDeclaration */: - case 214 /* ClassDeclaration */: + case 219 /* EnumDeclaration */: + case 216 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 192 /* Block */: + case 194 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // fall through. - case 244 /* CatchClause */: + case 246 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 220 /* CaseBlock */: + case 222 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -51012,7 +51831,7 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 197 /* DoStatement */) { + if (node.parent.kind === 199 /* DoStatement */) { // Go to while keyword and do action instead return spanInPreviousNode(node); } @@ -51022,17 +51841,17 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 175 /* FunctionExpression */: + case 215 /* FunctionDeclaration */: + case 176 /* ArrowFunction */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: case 145 /* GetAccessor */: case 146 /* SetAccessor */: case 144 /* Constructor */: - case 198 /* WhileStatement */: - case 197 /* DoStatement */: - case 199 /* ForStatement */: + case 200 /* WhileStatement */: + case 199 /* DoStatement */: + case 201 /* ForStatement */: return spanInPreviousNode(node); // Default to parent node default: @@ -51041,19 +51860,19 @@ var ts; } function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration - if (ts.isFunctionLike(node.parent) || node.parent.kind === 245 /* PropertyAssignment */) { + if (ts.isFunctionLike(node.parent) || node.parent.kind === 247 /* PropertyAssignment */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 171 /* TypeAssertionExpression */) { + if (node.parent.kind === 173 /* TypeAssertionExpression */) { return spanInNode(node.parent.expression); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 197 /* DoStatement */) { + if (node.parent.kind === 199 /* DoStatement */) { // Set span on while expression return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); } @@ -51082,6 +51901,9 @@ var ts; /// /* @internal */ var debugObjectHost = this; +// We need to use 'null' to interface with the managed side. +/* tslint:disable:no-null */ +/* tslint:disable:no-in-operator */ /* @internal */ var ts; (function (ts) { @@ -51093,7 +51915,6 @@ var ts; var ScriptSnapshotShimAdapter = (function () { function ScriptSnapshotShimAdapter(scriptSnapshotShim) { this.scriptSnapshotShim = scriptSnapshotShim; - this.lineStartPositions = null; } ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { return this.scriptSnapshotShim.getText(start, end); @@ -51119,7 +51940,7 @@ var ts; } }; return ScriptSnapshotShimAdapter; - })(); + }()); var LanguageServiceShimHostAdapter = (function () { function LanguageServiceShimHostAdapter(shimHost) { var _this = this; @@ -51137,6 +51958,9 @@ var ts; }); }; } + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } LanguageServiceShimHostAdapter.prototype.log = function (s) { if (this.loggingEnabled) { @@ -51174,11 +51998,6 @@ var ts; return this.files = JSON.parse(encoded); }; LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { - // Shim the API changes for 1.5 release. This should be removed once - // TypeScript 1.5 has shipped. - if (this.files && this.files.indexOf(fileName) < 0) { - return undefined; - } var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); }; @@ -51206,17 +52025,10 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { - // Wrap the API changes for 1.5 release. This try/catch - // should be removed once TypeScript 1.5 has shipped. - try { - return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); - } - catch (e) { - return ""; - } + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; return LanguageServiceShimHostAdapter; - })(); + }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; /** A cancellation that throttles calls to the host */ var ThrottledCancellationToken = (function () { @@ -51238,23 +52050,17 @@ var ts; return false; }; return ThrottledCancellationToken; - })(); + }()); var CoreServicesShimHostAdapter = (function () { function CoreServicesShimHostAdapter(shimHost) { + var _this = this; this.shimHost = shimHost; + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude) { - // Wrap the API changes for 1.5 release. This try/catch - // should be removed once TypeScript 1.5 has shipped. - // Also consider removing the optional designation for - // the exclude param at this time. - var encoded; - try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); - } - catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension); - } + var encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -51264,18 +52070,19 @@ var ts; return this.shimHost.readFile(fileName); }; return CoreServicesShimHostAdapter; - })(); + }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; function simpleForwardCall(logger, actionDescription, action, logPerformance) { + var start; if (logPerformance) { logger.log(actionDescription); - var start = Date.now(); + start = Date.now(); } var result = action(); if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); - if (typeof (result) === "string") { + if (typeof result === "string") { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; @@ -51308,7 +52115,7 @@ var ts; this.factory.unregisterShim(this); }; return ShimBase; - })(); + }()); function realizeDiagnostics(diagnostics, newLine) { return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); } @@ -51357,9 +52164,7 @@ var ts; * Update the list of scripts known to the compiler */ LanguageServiceShimObject.prototype.refresh = function (throwOnError) { - this.forwardJSONCall("refresh(" + throwOnError + ")", function () { - return null; - }); + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); }; LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { var _this = this; @@ -51374,33 +52179,25 @@ var ts; }; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { var _this = this; @@ -51430,10 +52227,7 @@ var ts; */ LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { - var quickInfo = _this.languageService.getQuickInfoAtPosition(fileName, position); - return quickInfo; - }); + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); }; /// NAMEORDOTTEDNAMESPAN /** @@ -51442,10 +52236,7 @@ var ts; */ LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { var _this = this; - return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { - var spanInfo = _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); - return spanInfo; - }); + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); }; /** * STATEMENTSPAN @@ -51453,18 +52244,12 @@ var ts; */ LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { - var spanInfo = _this.languageService.getBreakpointStatementAtPosition(fileName, position); - return spanInfo; - }); + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; /// SIGNATUREHELP LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { - var signatureInfo = _this.languageService.getSignatureHelpItems(fileName, position); - return signatureInfo; - }); + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); }); }; /// GOTO DEFINITION /** @@ -51473,9 +52258,7 @@ var ts; */ LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; /// GOTO Type /** @@ -51484,29 +52267,20 @@ var ts; */ LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getTypeDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { - return _this.languageService.getRenameInfo(fileName, position); - }); + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); }; LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { var _this = this; - return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { - return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); - }); + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); }; /// GET BRACE MATCHING LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { - var textRanges = _this.languageService.getBraceMatchingAtPosition(fileName, position); - return textRanges; - }); + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); }; /// GET SMART INDENT LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { @@ -51519,21 +52293,15 @@ var ts; /// GET REFERENCES LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getReferencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { var _this = this; - return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { - return _this.languageService.findReferences(fileName, position); - }); + return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); }); }; LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getOccurrencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { var _this = this; @@ -51552,41 +52320,32 @@ var ts; */ LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { - var completion = _this.languageService.getCompletionsAtPosition(fileName, position); - return completion; - }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); }; /** Get a string based representation of a completion list entry details */ LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", " + entryName + ")", function () { - var details = _this.languageService.getCompletionEntryDetails(fileName, position, entryName); - return details; - }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); - return edits; + return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForDocument(fileName, localOptions); - return edits; + return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); - return edits; + return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { @@ -51597,45 +52356,27 @@ var ts; /** Return a list of symbols that are interesting to navigate to */ LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount) { var _this = this; - return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { - var items = _this.languageService.getNavigateToItems(searchValue, maxResultCount); - return items; - }); + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; - return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { - var items = _this.languageService.getNavigationBarItems(fileName); - return items; - }); + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; - return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { - var items = _this.languageService.getOutliningSpans(fileName); - return items; - }); + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); }; LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { var _this = this; - return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { - var items = _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); - return items; - }); + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); }; /// Emit LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { var _this = this; - return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { - var output = _this.languageService.getEmitOutput(fileName); - // Shim the API changes for 1.5 release. This should be removed once - // TypeScript 1.5 has shipped. - output.emitOutputStatus = output.emitSkipped ? 1 : 0; - return output; - }); + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); }; return LanguageServiceShimObject; - })(ShimBase); + }(ShimBase)); function convertClassifications(classifications) { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } @@ -51654,17 +52395,17 @@ var ts; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); - var items = classification.entries; var result = ""; - for (var i = 0; i < items.length; i++) { - result += items[i].length + "\n"; - result += items[i].classification + "\n"; + for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { + var item = _a[_i]; + result += item.length + "\n"; + result += item.classification + "\n"; } result += classification.finalLexState; return result; }; return ClassifierShimObject; - })(ShimBase); + }(ShimBase)); var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { @@ -51723,24 +52464,22 @@ var ts; return { options: {}, files: [], - errors: [realizeDiagnostic(result.error, '\r\n')] + errors: [realizeDiagnostic(result.error, "\r\n")] }; } var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(ts.normalizeSlashes(fileName))); return { options: configFile.options, files: configFile.fileNames, - errors: realizeDiagnostics(configFile.errors, '\r\n') + errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); }; CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { - return this.forwardJSONCall("getDefaultCompilationSettings()", function () { - return ts.getDefaultCompilerOptions(); - }); + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); }); }; return CoreServicesShimObject; - })(ShimBase); + }(ShimBase)); var TypeScriptServicesFactory = (function () { function TypeScriptServicesFactory() { this._shims = []; @@ -51802,12 +52541,14 @@ var ts; throw new Error("Invalid operation"); }; return TypeScriptServicesFactory; - })(); + }()); ts.TypeScriptServicesFactory = TypeScriptServicesFactory; if (typeof module !== "undefined" && module.exports) { module.exports = ts; } })(ts || (ts = {})); +/* tslint:enable:no-in-operator */ +/* tslint:enable:no-null */ /// TODO: this is used by VS, clean this up on both sides of the interface /* @internal */ var TypeScript; @@ -51817,5 +52558,9 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); +/* tslint:disable:no-unused-variable */ +// '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.6"; +var toolsVersion = "1.8"; +/* tslint:enable:no-unused-variable */